File upload in Django +ajax detailed application

Source: Internet
Author: User

"001" Uploading files based on Ajax

Principle: If we use AJAX operations when it comes to file uploads, use Formdata

1. The first thing to understand: the type of upload file using input box is file: 2. Backstage I need to get the file object passed by the front end, note that the file object is not inside the request.post, but inside the request.files:
= Request. FILES. Get ("cFile")

3.contentType: I said in the previous section that the client tells the server to decide what data encoding format to send to the server, in the request header, if the parameter is not specifically specified, then the default is to assemble the data in the form of urlencoded for us.

Note that ContentType is a front-end page that sends data to the server, specifically in what format to assemble the data, and then sends the past, depending on the type of contenttype, the default is the following type, which is assembled in the form of key-value pairs of key-value pairs:

4. According to the above, now I want to transfer a file in the past, because the key value pairs involved in a file, if the default encoding is sent in the past, we print request.body on the server, we can only get a file name:

This obviously does not meet our requirements, because we need the file object. So we can't send the data by default, because it involves binary data, how to set it? Yesterday I used Ajax to specify parameters directly, and now I use the form form to pass data including binary files, so I need to add a parameter: enctype, here we check Multipart/form-data, as follows:

I later upload pictures, music and other binary files, can be used in conjunction with Form-data, when we modify the format, we can look at the request header in the Content-type:

Then take a look at the print results on the server side:

Request. Files receive the file object, Inmemoryuploadfile is we get the file handle, so upload avatar!

The above example shows that Form-data can support both form data, such as we print request. Post prints out form data, and supports binary data, examples, audio, and other files. However, urlencoded only supports form data. This is the fundamental difference between the two, be sure to distinguish between open.

Request. Files is a dictionary, and now we get a file object:

The name of the picture is printed by the Name property of the file handle:

Remember to use Ajax to upload a file, input box type to be changed to button, do not use submit.

$ ("button") represents the <button> element and <input> element that select Type= "button".

Get the binary file object through jquery:

when uploading a binary file using AJAX, note the value when you assemble the key pairs:1. First use jquery to get the input tag that the file belongs to:$ ("#cFile") 2. Convert the jquery object to a DOM object:$ ("#cFile") [0] At this point we get the DOM object 3. Call the files method of the DOM object, get a file list:filelist, and then only need to getThe first element of the list of files can be: $ ("#cFile") [0].files[0] to get to a file object

4. Can we write it in the following way?

In the way described above, the direct error is written as follows:

That is because you send binary data, according to the form of data sent must not be, so certainly not in accordance with the above way, then Ajax is Formdata, to use Ajax to upload binary files need to use to formdata, we do not need any form form, becomes as follows:

Send the data using the following form:

Pass the Formdata directly to the past. Click Send still have the problem, that is because content-type default is urlencoded, now I use Ajax send, that will change two parameters, are set to False

As we said before, no matter what data you write, Ajax will transmit your data in the format specified in ContentType, and it will be sent to you by default urlencoded, so I send the past in urlencoded format; If you change to JSON , I'll send it in JSON format. But not all situations require code transfer, for example, I pass a binary file, binary is not necessary to encode, according to the original file format to send. When Ajax sends the data, it first looks at the value of the ProcessData, if true, indicates that I need to process the data to send, as to what kind of processing, you have to ask ContentType, ContentType will tell Ajax whether the data is processed into a urlencoded form, or a JSON string, that is, a combination of the two, if the setting ProcessData is false, indicating what my data looks like, you send it to the server, Let the server accept it itself. So the value of ProcessData is only two, True: I am the data preprocessing, as to how to deal with, is contenttype to do, for false, then tell Ajax do not do processing, directly send binary data can. So ProcessData is set to False, then contenttype is useless, directly set to False, the default urlencoded is emptied out, if you do not set, then it is sent by default urlencoded.
Now you do not use form form (urlencoded) in the form of sending, then I transfer csrf_token is also binary, that must not pass, so we have to add a request headerX-csrftoken:

Here is the value in the input box in the Web page, so using Csrfmiddlewaretoken, if you take a value from a cookie, you have to use Csrftoken, which you should pay attention to.

In summary, there are two forms of uploading files:

Summary: There are two ways to upload a file:"01". Form form data is submitted:two modifications: 1. Add a property after the form label enctype= "Multipart/form-data"2. Since the uploaded file is binary data, you also need to modify the contenttype so that it becomesFormdata:

"02" Commits using Ajax:

1. Instantiate the form data object:

Whether the data in this case is form data or non-form data can be

2. Then send the past as the result of Formdata instantiation:

Finally, I would like to share a practical example for you to refer to:

$ (document). Ready (function () {//The blur event that is bound for each input box and sends the value through Ajax to the background for validation$("#id_username"). blur (function () {$.ajax ({URL:"/validate_username/", type:"Get", data:{"username": $("#id_username"). Val ()}, Success:function (data) {if(Data.flag) {alert ("This username has Benn registered"); //$ ("#error"). HTML ("User name has been registered");}Else{console.log (Data.flag);        }            }        }); $("#register_btn"). Submit ();      }); varHandlerpopup =function (captchaobj) {//a successful callbackcaptchaobj.onsuccess (function () {function foo () {$ (". Error"). HTML (""); }            varValidate =captchaobj.getvalidate (); var$formData =NewFormData (); $formData. Append ("username",$('#id_username'). Val ()); $formData. Append ("Password", $("#id_password"). Val ()); $formData. Append ("Password_again", $("#id_password_again"). Val ()); $formData. Append ("Email", $("#id_email"). Val ()); $formData. Append ("Mobile", $("#id_mobile"). Val ()); $formData. Append ("Avatar_image", $("#avatar_file")[0].files[0]); $formData. Append ("Csrfmiddlewaretoken", $("input[name= ' Csrfmiddlewaretoken ']"). Val ()); $formData. Append ("Geetest_challenge", Validate.geetest_challenge); $formData. Append ("geetest_validate", validate.geetest_validate); $formData. Append ("Geetest_seccode", Validate.geetest_seccode); $.ajax ({URL:"/pc-geetest/ajax_register_validate",//perform two validationsType"Post", DataType:"JSON", data: $formData, ProcessData:false, ContentType:false, Success:function (data) {if(Data && (data.status = = ="Success")) {                        //Registration Data Meet the rules, prompt registration of successful information, 3 seconds after the jump to the login interface$("#register_success"). HTML ("Congratulations for Register"); SetTimeout (foo, the); } Else {                        //the registration data does not satisfy the rule, then prompts the error message, error_msg is a dictionary//when the first hint of 3 field errors, I modified an error, then there are 2 left, just the other one//The error should disappear because this is another AJAX request. $("span"). HTML (""); $(". Form-group Div"). each (function () {//Second, the input box should be the wrong red hint to eliminate, according to the following, we should be input box of the parent tag Div$( This). Removeclass ("Has-error");                        });                            $.each (data.error_msg, function (key, value) {Console.log (data.error_msg); //1. Create a new span tag and add the appropriate style$span = $ ("<span>"); $span. addclass ("Pull-right"). CSS ("Color","Red"). HTML (value[0]); //2. Place the span tag below the corresponding input input box and implement it through $ ("#id_" +key)//The . Parent () is the parent label of the input tag, and to make the entire input box red, you must have a div$("#id_"+key). After ($span). Parent (). AddClass ("Has-error"); //3. Determine if the password defined in the Global hook function is incorrect                            if(Key = = ="__all__"){                                $("#id_password_again"). After ($span). Parent (). AddClass ("Has-error");        }                        })                    }                }            });        }); $("#popup-submit"). Click (function () {captchaobj.show ();        }); //Add the verification code to the element with ID captchaCaptchaobj.appendto ("#popup-captcha");     }; //Verify that you need to get id,challenge,success (whether failback is enabled) to the website master background$.ajax ({URL:"/pc-geetest/register?t="+ (NewDate ()). GetTime (),//add random number to prevent cachingType"Get", DataType:"JSON", Success:function (data) {initgeetest ({gt:data.gt, Challenge:dat A.challenge, Product:"Popup", Offline:!data.success}, Handlerpopup); }    });});

Django File Upload: https://www.cnblogs.com/linjiqin/p/3731751.html

Https://www.cnblogs.com/zhaopengcheng/p/5633154.html

http://blog.csdn.net/a18852867035/article/details/66976028

Https://www.cnblogs.com/nulige/p/6582355.html

 

File upload in Django +ajax detailed application

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.