Recently, a friend asked me how to use js to obtain the information of the uploaded image and then transfer it to the backend through ajax? Search for a large amount of information online. The following small series will sort out my solutions and share them with you. If you need them, refer to the project requirements below: how to get the uploaded image information (temporary save path, name, size) through js and then pass it to the backend through ajax
Subject received with jquery
The method is as follows:
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 information about 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 passed using post?
When I saw this question, I thought it was not easy. I directly used file to parse strings from an object through JSON. stringify (file) (Note: stringify (). 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 output is: {}$. post ('', file_json );}
I found that the printed object is an empty object: {}; I am grateful for the trouble!
So I used the uploadfile plug-in or Baidu's webuploader for another idea. jQuery File Upload is a Jquery Image Upload Component that supports uploading, canceling, and deleting multiple files, preview thumbnails and display the image size in the list before uploading. the upload progress bar can be displayed. servers developed in various dynamic languages are supported.
If html5 is supported, you can use FormData Ajax for upload.
The above content is the method used by the editor to obtain the uploaded image information (temporary save path, name, size) through js and then pass it to the backend through ajax, hoping to help you.