際際滷

際際滷Share a Scribd company logo
Handling Files

  Thierry Sans
MIME Types
MIME types




   MIME (Multipurpose Internet Mail Extensions) is also known
    as the content type

   De鍖ne the format of a document exchanged on internet
    (IETF standard) http://www.iana.org/assignments/media-types/index.html
Examples of MIME types


    text/html

    text/css

    text/javascript

    image/jpeg - image/gif - image/svg - image/png (and so on)

    application/pdf

    application/json
Example of how images are retrieved

    http://www.example.com//hello/bart/
    http://localhost/HelloYou/
Example of how images are retrieved
                                          GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/




                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/


                                                                             MIME : text/html
                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/


                                                                             MIME : text/html
                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>




                                          GET images/bart.jpg
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/


                                                                             MIME : text/html
                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>




                                          GET images/bart.jpg
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/


                                                                             MIME : text/html
                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>




                                          GET images/bart.jpg




                                                                                MIME : image/jpg
Example of how images are retrieved
                                             GET hello/bart/
    http://www.example.com//hello/bart/
    http://localhost/HelloYou/


                                                                             MIME : text/html
                                          <html>
                                             <body>
                                                <img src=/slideshow/files-9553232/9553232/images/bart.jpg/>
                                             </body>
                                          </html>




                                          GET images/bart.jpg




                                                                                MIME : image/jpg
Client Side
Uploading a 鍖l艶
Upload FORM

this form handles multiple
formats of data
                             the URL to submit the form
                                                            uploading 鍖l艶s must be done
                                                            through a POST request



     <form enctype="multipart/form-data" action="add/" method="post">
       <input id="upload" type="file" name="file"/>
       <input type="text" name="name"/>
       <input type="text" name="webpage"/>
     </form>
     <a href="#" onclick="submit();return false;">Submit</a>

                                      WebDirectory/templates/WebDirectory/index.html
Submitting the form with Javascript



                                WebDirectory/static/js/script.js
 function publish(){
     $("form").submit();
 }
Using dragn drop ...
Using dragn drop ...




                        ... thats your homework :)
Server Side
Saving and serving uploaded 鍖l艶s
Saving uploaded 鍖l艶s




                       def add(request):
                            ...




                       Controller
Saving uploaded 鍖l艶s




                       def add(request):
     POST add/              ...




                       Controller
Saving uploaded 鍖l艶s

                                                         uploads
      The image is stored in the upload directory




                                     def add(request):
     POST add/                            ...




                                     Controller
Saving uploaded 鍖l艶s

                                                                           uploads
             The image is stored in the upload directory




                                            def add(request):
           POST add/                             ...



                                                                 img      mime       name     url

                                                                 path   image/png   Khaled http://

                                                                 path   image/jpg   Kemal   http://

                                            Controller
                                                                Database
The image path and the mime type are stored in the database
Con鍖guring Django


   Create a directory upload in your Django project

   Con鍖gure your project (edit settings.py)


                                                                          settings.py
    # Absolute filesystem path to the directory that will hold user-uploaded files.
    # Example: "/home/media/media.lawrence.com/media/"
    MEDIA_ROOT = os.path.join(PROJECT_PATH, 'uploads/')
The model


                                              WebDirectory/models.py

 class Entry(models.Model):
     # image = models.CharField(max_length=200)
     image = models.ImageField(upload_to='WebDirectory')
     mimeType = models.CharField(max_length=20)
    name = models.CharField(max_length=200)
    webpage = models.URLField(max_length=200)
The model

          use FileField for generic 鍖l艶s
                                              WebDirectory/models.py

 class Entry(models.Model):
     # image = models.CharField(max_length=200)
     image = models.ImageField(upload_to='WebDirectory')
     mimeType = models.CharField(max_length=20)
    name = models.CharField(max_length=200)
    webpage = models.URLField(max_length=200)
The model

          use FileField for generic 鍖l艶s
                                              WebDirectory/models.py

 class Entry(models.Model):
     # image = models.CharField(max_length=200)
     image = models.ImageField(upload_to='WebDirectory')
     mimeType = models.CharField(max_length=20)
    name = models.CharField(max_length=200)
    webpage = models.URLField(max_length=200)
                                                      where to store
                                                      uploaded 鍖l艶s
The model

             use FileField for generic 鍖l艶s
                                                  WebDirectory/models.py

   class Entry(models.Model):
        # image = models.CharField(max_length=200)
        image = models.ImageField(upload_to='WebDirectory')
        mimeType = models.CharField(max_length=20)
        name = models.CharField(max_length=200)
        webpage = models.URLField(max_length=200)
                                                          where to store
                                                          uploaded 鍖l艶s
We need to record the MIME type
(see serving uploaded 鍖l艶)
Cleaning the WebDirectory database


   When the model (i.e. the database schema) changes

   The WebDirectory database must be reset

       remove the existing records

       recreate the tables


    $ python manage.py reset WebDirectory
Controller - saving uploaded 鍖l艶s


                                                   WebDirectory/views.py

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def add(request):
 e = Entry(image=request.FILES['file'],
            mimeType=request.FILES['file'].content_type,
            name=request.POST['name'], 
            webpage = request.POST['webpage'])
 e.save()
  return HttpResponseRedirect(reverse('WebDirectory.views.index',))
Controller - saving uploaded 鍖l艶s


                                                    WebDirectory/views.py

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt                         get the 鍖l艶 from the HTTP request
def add(request):
 e = Entry(image=request.FILES['file'],
            mimeType=request.FILES['file'].content_type,
            name=request.POST['name'], 
            webpage = request.POST['webpage'])
 e.save()
  return HttpResponseRedirect(reverse('WebDirectory.views.index',))
Controller - saving uploaded 鍖l艶s

Not secure but we will
talk about security later
                                                           WebDirectory/views.py

 from django.views.decorators.csrf import csrf_exempt


 @csrf_exempt                               get the 鍖l艶 from the HTTP request
 def add(request):
    e = Entry(image=request.FILES['file'],
                   mimeType=request.FILES['file'].content_type,
                   name=request.POST['name'], 
                   webpage = request.POST['webpage'])
    e.save()
    return HttpResponseRedirect(reverse('WebDirectory.views.index',))
Controller - saving uploaded 鍖l艶s

Not secure but we will
talk about security later
                                                           WebDirectory/views.py

 from django.views.decorators.csrf import csrf_exempt


 @csrf_exempt                               get the 鍖l艶 from the HTTP request
 def add(request):
    e = Entry(image=request.FILES['file'],
                   mimeType=request.FILES['file'].content_type,
                   name=request.POST['name'], 
                   webpage = request.POST['webpage'])     get the MIME type
    e.save()
    return HttpResponseRedirect(reverse('WebDirectory.views.index',))
Controller - serving uploaded 鍖l艶s




   How to serve these uploaded 鍖l艶s?

   Should we serve them as static 鍖l艶s?
Why not serving uploaded 鍖l艶s as static 鍖l艶s?



   Because we want to control

       who can access these 鍖l艶s

       when to serve these 鍖l艶s

       how to serve these 鍖l艶s
A good way to serve uploaded 鍖l艶s



   Have a method to control (controller) the 鍖l艶 - getImage

   Reference the image using an identi鍖er

       automatically generated hash code

       or database entry id (primary key in the database)
How to de鍖ne getImage




                 def
                 getimage(request,imageid):
                      ...




                 Controller
How to de鍖ne getImage




     GET getimage/345/
                         def
                         getimage(request,imageid):
                              ...




                         Controller
How to de鍖ne getImage




     GET getimage/345/
                               def
                               getimage(request,imageid):
                                    ...



                                                             img      mime      name      url

                                                             path   image/png   Khaled http://

                                                             path   image/jpg   Kemal   http://
                              Controller

                                                            Database
           Get the image path and mime type
           from the database based on its id
How to de鍖ne getImage

                                                                           uploads
     Retrieve the image from the upload directory
     (this is done automatically by Django)



     GET getimage/345/
                                   def
                                   getimage(request,imageid):
                                        ...



                                                                 img      mime       name     url

                                                                 path   image/png   Khaled http://

                                                                 path   image/jpg   Kemal   http://
                                   Controller

                                                                Database
              Get the image path and mime type
              from the database based on its id
How to de鍖ne getImage

                                                                                    uploads
              Retrieve the image from the upload directory
              (this is done automatically by Django)



              GET getimage/345/
                                            def
                                            getimage(request,imageid):
                                                 ...



                                                                          img      mime       name     url

                                                                          path   image/png   Khaled http://

Return a HTTP response of the                                             path   image/jpg   Kemal   http://
corresponding mime type                     Controller

                                                                         Database
                       Get the image path and mime type
                       from the database based on its id
Updating the image URL in the template
                                      WebDirectory/templates/WebDirectory/index.html

...
<div id="directory">
 {% if entry_list %}
      {% for entry in entry_list %}
        <div class="entry">
            <div class="image"><img src=/slideshow/files-9553232/9553232/"getimage/{{entry.id}}/"/>
          </div>
          <div class="name">{{entry.name}}</div>
          <div class="website">
            <a href="{{entry.webpage}}">{{entry.name}}'s website</a>
...
Controller - serving uploaded 鍖l艶s




                                                 WebDirectory/views.py

def getImage(request,imageid):
   e = Entry.objects.get(id=imageid)
   return HttpResponse(e.image, mimetype=e.mimeType)
Controller - serving uploaded 鍖l艶s




                    get the 鍖l艶 from the database
                                                    WebDirectory/views.py

def getImage(request,imageid):
   e = Entry.objects.get(id=imageid)
   return HttpResponse(e.image, mimetype=e.mimeType)
Controller - serving uploaded 鍖l艶s




                    get the 鍖l艶 from the database
                                                       WebDirectory/views.py

def getImage(request,imageid):
   e = Entry.objects.get(id=imageid)
   return HttpResponse(e.image, mimetype=e.mimeType)



                                 return an HTTP response of
                                 the corresponding MIME type

More Related Content

Files

  • 1. Handling Files Thierry Sans
  • 3. MIME types MIME (Multipurpose Internet Mail Extensions) is also known as the content type De鍖ne the format of a document exchanged on internet (IETF standard) http://www.iana.org/assignments/media-types/index.html
  • 4. Examples of MIME types text/html text/css text/javascript image/jpeg - image/gif - image/svg - image/png (and so on) application/pdf application/json
  • 5. Example of how images are retrieved http://www.example.com//hello/bart/ http://localhost/HelloYou/
  • 6. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/
  • 7. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html>
  • 8. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ MIME : text/html <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html>
  • 9. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ MIME : text/html <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html> GET images/bart.jpg
  • 10. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ MIME : text/html <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html> GET images/bart.jpg
  • 11. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ MIME : text/html <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html> GET images/bart.jpg MIME : image/jpg
  • 12. Example of how images are retrieved GET hello/bart/ http://www.example.com//hello/bart/ http://localhost/HelloYou/ MIME : text/html <html> <body> <img src=/slideshow/files-9553232/9553232/images/bart.jpg/> </body> </html> GET images/bart.jpg MIME : image/jpg
  • 14. Upload FORM this form handles multiple formats of data the URL to submit the form uploading 鍖l艶s must be done through a POST request <form enctype="multipart/form-data" action="add/" method="post"> <input id="upload" type="file" name="file"/> <input type="text" name="name"/> <input type="text" name="webpage"/> </form> <a href="#" onclick="submit();return false;">Submit</a> WebDirectory/templates/WebDirectory/index.html
  • 15. Submitting the form with Javascript WebDirectory/static/js/script.js function publish(){ $("form").submit(); }
  • 17. Using dragn drop ... ... thats your homework :)
  • 18. Server Side Saving and serving uploaded 鍖l艶s
  • 19. Saving uploaded 鍖l艶s def add(request): ... Controller
  • 20. Saving uploaded 鍖l艶s def add(request): POST add/ ... Controller
  • 21. Saving uploaded 鍖l艶s uploads The image is stored in the upload directory def add(request): POST add/ ... Controller
  • 22. Saving uploaded 鍖l艶s uploads The image is stored in the upload directory def add(request): POST add/ ... img mime name url path image/png Khaled http:// path image/jpg Kemal http:// Controller Database The image path and the mime type are stored in the database
  • 23. Con鍖guring Django Create a directory upload in your Django project Con鍖gure your project (edit settings.py) settings.py # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_PATH, 'uploads/')
  • 24. The model WebDirectory/models.py class Entry(models.Model): # image = models.CharField(max_length=200) image = models.ImageField(upload_to='WebDirectory') mimeType = models.CharField(max_length=20) name = models.CharField(max_length=200) webpage = models.URLField(max_length=200)
  • 25. The model use FileField for generic 鍖l艶s WebDirectory/models.py class Entry(models.Model): # image = models.CharField(max_length=200) image = models.ImageField(upload_to='WebDirectory') mimeType = models.CharField(max_length=20) name = models.CharField(max_length=200) webpage = models.URLField(max_length=200)
  • 26. The model use FileField for generic 鍖l艶s WebDirectory/models.py class Entry(models.Model): # image = models.CharField(max_length=200) image = models.ImageField(upload_to='WebDirectory') mimeType = models.CharField(max_length=20) name = models.CharField(max_length=200) webpage = models.URLField(max_length=200) where to store uploaded 鍖l艶s
  • 27. The model use FileField for generic 鍖l艶s WebDirectory/models.py class Entry(models.Model): # image = models.CharField(max_length=200) image = models.ImageField(upload_to='WebDirectory') mimeType = models.CharField(max_length=20) name = models.CharField(max_length=200) webpage = models.URLField(max_length=200) where to store uploaded 鍖l艶s We need to record the MIME type (see serving uploaded 鍖l艶)
  • 28. Cleaning the WebDirectory database When the model (i.e. the database schema) changes The WebDirectory database must be reset remove the existing records recreate the tables $ python manage.py reset WebDirectory
  • 29. Controller - saving uploaded 鍖l艶s WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt def add(request): e = Entry(image=request.FILES['file'], mimeType=request.FILES['file'].content_type, name=request.POST['name'], webpage = request.POST['webpage']) e.save() return HttpResponseRedirect(reverse('WebDirectory.views.index',))
  • 30. Controller - saving uploaded 鍖l艶s WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the 鍖l艶 from the HTTP request def add(request): e = Entry(image=request.FILES['file'], mimeType=request.FILES['file'].content_type, name=request.POST['name'], webpage = request.POST['webpage']) e.save() return HttpResponseRedirect(reverse('WebDirectory.views.index',))
  • 31. Controller - saving uploaded 鍖l艶s Not secure but we will talk about security later WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the 鍖l艶 from the HTTP request def add(request): e = Entry(image=request.FILES['file'], mimeType=request.FILES['file'].content_type, name=request.POST['name'], webpage = request.POST['webpage']) e.save() return HttpResponseRedirect(reverse('WebDirectory.views.index',))
  • 32. Controller - saving uploaded 鍖l艶s Not secure but we will talk about security later WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the 鍖l艶 from the HTTP request def add(request): e = Entry(image=request.FILES['file'], mimeType=request.FILES['file'].content_type, name=request.POST['name'], webpage = request.POST['webpage']) get the MIME type e.save() return HttpResponseRedirect(reverse('WebDirectory.views.index',))
  • 33. Controller - serving uploaded 鍖l艶s How to serve these uploaded 鍖l艶s? Should we serve them as static 鍖l艶s?
  • 34. Why not serving uploaded 鍖l艶s as static 鍖l艶s? Because we want to control who can access these 鍖l艶s when to serve these 鍖l艶s how to serve these 鍖l艶s
  • 35. A good way to serve uploaded 鍖l艶s Have a method to control (controller) the 鍖l艶 - getImage Reference the image using an identi鍖er automatically generated hash code or database entry id (primary key in the database)
  • 36. How to de鍖ne getImage def getimage(request,imageid): ... Controller
  • 37. How to de鍖ne getImage GET getimage/345/ def getimage(request,imageid): ... Controller
  • 38. How to de鍖ne getImage GET getimage/345/ def getimage(request,imageid): ... img mime name url path image/png Khaled http:// path image/jpg Kemal http:// Controller Database Get the image path and mime type from the database based on its id
  • 39. How to de鍖ne getImage uploads Retrieve the image from the upload directory (this is done automatically by Django) GET getimage/345/ def getimage(request,imageid): ... img mime name url path image/png Khaled http:// path image/jpg Kemal http:// Controller Database Get the image path and mime type from the database based on its id
  • 40. How to de鍖ne getImage uploads Retrieve the image from the upload directory (this is done automatically by Django) GET getimage/345/ def getimage(request,imageid): ... img mime name url path image/png Khaled http:// Return a HTTP response of the path image/jpg Kemal http:// corresponding mime type Controller Database Get the image path and mime type from the database based on its id
  • 41. Updating the image URL in the template WebDirectory/templates/WebDirectory/index.html ... <div id="directory"> {% if entry_list %} {% for entry in entry_list %} <div class="entry"> <div class="image"><img src=/slideshow/files-9553232/9553232/"getimage/{{entry.id}}/"/> </div> <div class="name">{{entry.name}}</div> <div class="website"> <a href="{{entry.webpage}}">{{entry.name}}'s website</a> ...
  • 42. Controller - serving uploaded 鍖l艶s WebDirectory/views.py def getImage(request,imageid): e = Entry.objects.get(id=imageid) return HttpResponse(e.image, mimetype=e.mimeType)
  • 43. Controller - serving uploaded 鍖l艶s get the 鍖l艶 from the database WebDirectory/views.py def getImage(request,imageid): e = Entry.objects.get(id=imageid) return HttpResponse(e.image, mimetype=e.mimeType)
  • 44. Controller - serving uploaded 鍖l艶s get the 鍖l艶 from the database WebDirectory/views.py def getImage(request,imageid): e = Entry.objects.get(id=imageid) return HttpResponse(e.image, mimetype=e.mimeType) return an HTTP response of the corresponding MIME type

Editor's Notes