Using formdata to upload attachments (two methods)
- VaR Reg = Document. getelementbyid ('reg ');
- VaR FD = new formdata (REG );
- Send (FD); // FD contains common form information and Attachment Information
Method 2
- VaR mypic = Document. getelementbyid ('myhead'). Files [0]; // obtain the file object of the file form
- FD. append ('myhead', mypic );
- Send (FD );
The new HTML5 standard obtains the attachment information files. We can use files to obtain the binary information of the image. After selecting the image file, the thumbnail will be displayed on the page immediately:
VaR mypic = Document. getelementbyid ('myhead'). Files [0];
Document. Images [0]. src = Window. url. createobjecturl (mypic); // obtain the image object and change its src attribute to the binary information of the selected image.
Select the file page to display the thumbnail immediately to display the upload progress:
<SCRIPT type = "text/JavaScript"> function F1 () {var mypic = document. getelementbyid ('myhead '). files [0]; // capture the Attachment Information on the page to upload var FD = new formdata (); FD. append ("myhead", mypic); var xhr = new XMLHttpRequest (); xhr. onreadystatechange = function () {If (xhr. readystate = 4 & xhr. status = 200) {alert (xhr. responsetext) ;}/// detects the current attachment upload status to process the upload progress and display the progress bar xhr. upload. onprogress = function (EVT) {// detects the attachment upload status // detects through the event object // this anonymous function expression is approximately 0.05 -Execute the command once in 0.1 seconds // console. log (EVT); // console. log (EVT. loaded); // the size of the uploaded file // EVT. total; total attachment size var loaded = EVT. loaded; var tot = EVT. total; var per = math. floor (100 * loaded/ToT); // percentage of uploaded files var son = document. getelementbyid ('son'); son. innerhtml = per + "%"; son. style. width = per + "%";} xhr. open ("Post ",". /04.php"); xhr. send (FD);} // immediately display the uploaded image function F2 () {// use files to obtain the uploaded attachment (image) Information var mypic = document. getelementbyid ('myhead '). Files [0]; // use mypic to obtain the image URL (Binary source code) // URL HTML5 New Standard attribute // window. URL. createobjecturl (mypic); document. getelementsbytagname ('img ') [0]. src = Window. URL. createobjecturl (mypic) ;}</SCRIPT> <style type = "text/CSS" ># parent {width: 550px; Height: 50px; Border: 5px solid blue ;} # son {width: 0; Height: 100%; Background-color: lightblue; text-align: center; line-Height: 50px; font-size: 20px; font-weight: bold ;}</style> <Div Id = "parent"> <Div id = "son"> </div> <! -- Used to display the upload progress bar --> User Profile: <input type = "file" id = "myhead" name = "myhead" onchange = "f2 () "/> <br/> <br/> <input type =" button "value =" Upload avatar "onclick =" F1 () "/> <br/>