python3-Development Advanced Add-on file upload in Django

Source: Internet
Author: User

PS: This time is a little out of state, just get back to that state, then we continue to dream

Today, let's add a few ways to upload files:

First, we first add a point of knowledge:

First, the request head contenttype:

ContentType refers to the type of the request body encoding, common types total three kinds:

1, application/x-www-form-urlencoded

This should be the most common way of post submission data. The native <form> form of the browser, and if you do not set enctype the property, the data will eventually be submitted in the application/x-www-form-urlencoded way. The request is similar to the following (extraneous request headers are omitted in this article):

POST http://www.example.com http/1.1Content-type:application/x-www-form-urlencoded;charset=utf-8  User=duoduo&age=22

2, Multipart/form-data

This is another common way of post data submission. When we use a form to upload a file, the enctype of the <form> form must be equal to Multipart/form-data

POST http://www.example.com http/1.1Content-type:multipart/form-data; boundary=----Webkitformboundaryrgkcby7qhfd3trwa------webkitformboundaryrgkcby7qhfd3trwacontent-disposition:form-data; Name="User"Duoduo------webkitformboundaryrgkcby7qhfd3trwacontent-disposition:form-data; Name="file"; Filename="Chrome.png"Content-type:image/pngpng ... content of chrome.png ...------webkitformboundaryrgkcby7qhfd3trwa--

This example is slightly more complicated. First, a boundary is created to split the different fields, so the boundary is very long and complex in order to avoid repetition with the body content. Then the content-type indicates that the data is encoded in Multipart/form-data, and what the boundary of this request is. In the message body, the number of fields is divided into several similar sections, each starting with a description of the --boundary content, followed by a carriage return, and finally a field-specific content (text or binary). If you are transferring files, include the file name and file type information. The message body ends with an --boundary-- indication. For a detailed definition of multipart/form-data, go to rfc1867 to view it.

This way is generally used to upload files, the major service-side language for it also has a good support.

The two types of POST data mentioned above are natively supported by the browser, and the native <form> forms in the current standard are only supported in both ways (by specifying the properties of the <form> element enctype , the default is application/x-www-form-urlencoded . Actually enctype support text/plain , but very little use).

With more and more Web sites, especially WebApp, all using Ajax to interact with data, we can define new ways to submit data, which is more convenient for development.

3, Application/json

Application/json this content-type as response head everybody certainly is not unfamiliar. In fact, more and more people now use it as a request header to tell the server that the message body is a serialized JSON string. Due to the popularity of the JSON specification, in addition to the low version of IE, the major browsers are natively supported json.stringify, the service-side language has a function of processing JSON, the use of JSON will not encounter any trouble.

The JSON format supports much more complex structured data than key-value pairs, which is also useful. Remember when I was doing a project a few years ago, the level of data that needed to be submitted was very deep, and I was committing the data JSON serialization later. But at the time I was using the JSON string as Val, still in the key-value pair, to be submitted in a x-www-form-urlencoded manner.

Second, the file upload based on form forms

Module section

<form action=""Method="Post"Enctype="Multipart/form-data">User name<input type="text"Name="User">Avatar<input type="file"Name="Avatar"> <input type="Submit"></form>

View section

def Index (Request):     Print (request.body)   # Raw Request body Data    Print (Request. Get)    #  GET request data    print(request. Post)   #  POST request data    print(request. files)  #  uploaded file data    return render (request,"index.html ")

Third, Ajax-based file upload

Module

<form>User name<input type="text"Id="User">Avatar<input type="file"Id="Avatar"> <input type="Button"Id="Ajax-submit"Value="Ajax-submit"></form><script>    $("#ajax-submit"). Click (function () {var formdata=new FormData (); Formdata.append ("User",$("#user"). Val ()); Formdata.append ("avatar_img",$("#avatar") [0].files[0]); $.ajax ({URL:"", type:"Post", Data:formdata, Processdata:false,//do not process data contenttype:false,//do not set content type Success:function (data) {Console.log (data)}}) })</script>

View

defIndex (Request):ifRequest.is_ajax ():Print(Request.body)#Raw Request body Data        Print(Request. GET)#GET Request Data        Print(Request. POST)#POST request Data        Print(Request. FILES)#uploaded file Data        returnHttpResponse ("OK")    returnRender (Request,"index.html")

Check the browser's request header:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryaWl9k5ZMiTAzx3FT

python3-Development Advanced Add-on file upload in Django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.