Project requirements: How to obtain the uploaded image information (temporary saving path, name, size) through js and then pass it to the backend through ajax
The subject uses jquery to receive
<input name="c_pic" id="c_pic" type="file" class="file">
The method used is:
var input = document.getElementById("c_pic"); input.addEventListener('change',readFile,false); function readFile(){ var file = this.files[0]; }
The subject wants to use the ajax post method to transmit the relevant information of the uploaded image to the backend. The received file is an object file. How can I convert it into a data format that can be transmitted using post?
When I saw this topic, I thought it was not easy. I directly passed 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); //打印出来是: {} $.post('',file_json); }
I found that what was printed was an empty object: {}; if you know anything about it, let me know, I would be grateful!
So I changed my mind and used the uploadfile plug-in or Baidu's webuploader. jQuery File Upload is a Jquery image upload component that supports multi-file upload, cancellation, deletion, thumbnail preview before upload, list display of image size, and support for uploading. Progress bar display; supports server-side development in various dynamic languages.
If it supports html5, you can use FormData Ajax to upload.
The above content is the method shared by the editor to obtain uploaded image information (temporary saving path, name, size) through js and then pass it to the backend through ajax. I hope it will be helpful to everyone.