SlideShare a Scribd company logo
1 of 44
Handling Files

  Thierry Sans
MIME Types
MIME types




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

➡   Define 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=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=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=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=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=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=images/bart.jpg/>
                                             </body>
                                          </html>




                                          GET images/bart.jpg




                                                                                MIME : image/jpg
Client Side
Uploading a file
Upload FORM

this form handles multiple
formats of data
                             the URL to submit the form
                                                            uploading files 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 drag’n drop ...
Using drag’n drop ...




                        ... that’s your homework :)
Server Side
Saving and serving uploaded files
Saving uploaded files




                       def add(request):
                            ...




                       Controller
Saving uploaded files




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




                       Controller
Saving uploaded files

                                                         uploads
      The image is stored in the upload directory




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




                                     Controller
Saving uploaded files

                                                                           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
Configuring Django


•   Create a directory upload in your Django project

•   Configure 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 files
                                              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 files
                                              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 files
The model

             use FileField for generic files
                                                  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 files
We need to record the MIME type
(see serving uploaded file)
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 files


                                                   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 files


                                                    WebDirectory/views.py

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt                         get the file 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 files

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

 from django.views.decorators.csrf import csrf_exempt


 @csrf_exempt                               get the file 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 files

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

 from django.views.decorators.csrf import csrf_exempt


 @csrf_exempt                               get the file 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 files




•   How to serve these uploaded files?

•   Should we serve them as static files?
Why not serving uploaded files as static files?



•   Because we want to control

    •   who can access these files

    •   when to serve these files

    •   how to serve these files
A good way to serve uploaded files



•   Have a method to control (controller) the file - getImage

•   Reference the image using an identifier

    •   automatically generated hash code

    •   or database entry id (primary key in the database)
How to define getImage




                 def
                 getimage(request,imageid):
                      ...




                 Controller
How to define getImage




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




                         Controller
How to define 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 define 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 define 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="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 files




                                                 WebDirectory/views.py

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




                    get the file 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 files




                    get the file 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

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Files

  • 1. Handling Files Thierry Sans
  • 3. MIME types • MIME (Multipurpose Internet Mail Extensions) is also known as the content type ➡ Define 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=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=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=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=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=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=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 files 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 drag’n drop ... ... that’s your homework :)
  • 18. Server Side Saving and serving uploaded files
  • 19. Saving uploaded files def add(request): ... Controller
  • 20. Saving uploaded files def add(request): POST add/ ... Controller
  • 21. Saving uploaded files uploads The image is stored in the upload directory def add(request): POST add/ ... Controller
  • 22. Saving uploaded files 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. Configuring Django • Create a directory upload in your Django project • Configure 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 files 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 files 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 files
  • 27. The model use FileField for generic files 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 files We need to record the MIME type (see serving uploaded file)
  • 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 files 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 files WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the file 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 files Not secure but we will talk about security later WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the file 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 files Not secure but we will talk about security later WebDirectory/views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt get the file 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 files • How to serve these uploaded files? • Should we serve them as static files?
  • 34. Why not serving uploaded files as static files? • Because we want to control • who can access these files • when to serve these files • how to serve these files
  • 35. A good way to serve uploaded files • Have a method to control (controller) the file - getImage • Reference the image using an identifier • automatically generated hash code • or database entry id (primary key in the database)
  • 36. How to define getImage def getimage(request,imageid): ... Controller
  • 37. How to define getImage GET getimage/345/ def getimage(request,imageid): ... Controller
  • 38. How to define 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 define 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 define 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="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 files WebDirectory/views.py def getImage(request,imageid): e = Entry.objects.get(id=imageid) return HttpResponse(e.image, mimetype=e.mimeType)
  • 43. Controller - serving uploaded files get the file 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 files get the file 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

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n