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

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

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