Home>

A friend recently asked me,Use js to get the information of the uploaded image and pass it to the backend through ajax.How to achieve it?Search a lot of information onlineLet's organize my solution,Share with everyone,

Project requirements:How to get uploaded picture information (temporary save path,Name, size) and then passed to the backend via ajax

Receive with jquery

<input name="c_pic" type="file">
</pre>
</div>
<p>
The method used is:
</p>
<div>
<pre>
var input=document.getelementbyid ("c_pic");
input.addeventlistener ("change", readfile, false);
function readfile () {
var file=this.files [0];
}

The owner wants to use ajax's post method to pass the relevant information of the uploaded image to the backend.The received file is an object file. How can I convert it to a data format that can be passed by post?

When I saw this topic, I thought it was not easy,Directly pass the file through json.stringify (file) (note:stringify () is used to parse a string from an object), the code is as follows:

var input=document.getelementbyid ("c_pic");
input.addeventlistener ("change", readfile, false);
function readfile () {
var file=this.files [0];
var file_json=json.stringify (file);
console.log (file_json);//The printout is:()
$.post ("", file_json);
}

I found that the printed object is an empty object:{};Grateful!

So a different idea is to use the uploadfile plugin or Baidu's webuploader, where jquery file upload is a jquery image upload component,Support multi-file upload, cancel, delete, thumbnail preview before upload, list display picture size,Support upload progress bar display;Server-side support for various dynamic language development.

If you support html5, you can also use formdata ajax upload.

  • Previous Ajax request Session invalidation problem
  • Next How to solve the inconsistent value of Ajax access changing session and the difference between GET and POST in HTTP protocol