SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 

Kürzlich hochgeladen (20)

Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 

Empfohlen

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
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

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...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

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

Hinweis der Redaktion

  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