JavaScript file fragment upload _javascript tips

Source: Internet
Author: User
Tags file upload

Html

<form method= "POST" name= "form" action= "/mupload/upload/" enctype= "Multipart/form-data" >
<input ' type= ' Hidden ' name= ' csrfmiddlewaretoken ' value= '/> <input id= ' file ' type= ' file ' name= ' file ' onchange= '
"/>
<input id= ' button ' name= ' Submit ' type= ' button ' value= ' upload ' onclick= ' chunk_upload (this)/>

JS method

var filesplitsize = 1024 * 1024;
var start=0,end=0;
var i=0; File segment upload function chunk_upload (button) {var xmlhttp = new XMLHttpRequest (); Xmlhttp.open ("POST", "/chunk_upload/upload/"
, false);
Xmlhttp.setrequestheader ("X-csrftoken", button.form[' Csrfmiddlewaretoken '].value);
var f = button.form;
var file = f[' file ' [' Files '][0];
var size=file.size;
End=start+filesplitsize; if (end>size) {i=-1; end=size} else{i+=1; end=end;}
<br>//cutting file segment by size var blob = File.slice (start, end);
Xmlhttp.setrequestheader (' CharSet ', ' utf-8 ');
Xmlhttp.setrequestheader ("FileMD5", fileMD5);
Xmlhttp.setrequestheader ("Start", start);
Xmlhttp.setrequestheader ("End", end);
Xmlhttp.send (BLOB); if (xmlhttp.status==200) {<br> if (end==size) {<br> var backtext=xmlhttp.responsetext;<br> alert ( Backtext);<br>}else{<br> alert ("Upload complete section" +i+ "section") <br> start=end;<br> chunk_upload (button); <br>}<br>}else{<br> alert ("Upload error");<br> chunk_upload (button);<br>}
}  

Main ideas:

Note Set the starting position and cutting size of the cut, through the XMLHttpRequest Send request (HTTP protocol to know).

If some tag data can be added to the protocol header: Xmlhttp.setrequestheader ("End");

Send protocol body xmlhttp.send (data);

Listen for the return code to determine whether the delivery is successful and take the next step.

Reset the cutting position, then recursively call itself start=end;chunk_upload (button);

Attention:

The relationship between the start of the cut and the end and the FileSize

Pure JS upload files asynchronously and return to upload progress

Pure JS Implementation of asynchronous upload file, asynchronous return file upload progress, 0.05 to 0.1 seconds callback upload progress, other details see code snippet below usage annotation

1. Simple Asynchronous upload function

;(function (window,document) {var myupload = function (option) {var file, fd = new FormData (), xhr = new XMLHttpRequest (),
Loaded, tot, per, uploadurl,input;
input = document.createelement ("input");
Input.setattribute (' id ', ' myupload-input ');
Input.setattribute (' type ', ' file ');
Input.setattribute (' name ', "files");
Input.click ();
Uploadurl = Option.uploadurl;
callback = Option.callback;
uploading = option.uploading;
Beforesend = Option.beforesend; input.onchange= function () {file = Input.files[0]; if (beforesend instanceof function) {if (beforesend (file) = False) {RE
Turn false;
} fd.append ("Files", file); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && Xhr.status =) {if (callback instanceof funct
ION) {callback (Xhr.responsetext);}}  //Investigate current attachment upload situation xhr.upload.onprogress = function (evt) {loaded = evt.loaded; tot = evt.total; per = Math.floor (* loaded /tot);
Percentage already uploaded if (uploading instanceof Function) {uploading (per);};
Xhr.open ("Post", Uploadurl); XhR.send (FD);
}
};
Window.myupload = Myupload;
}) (window,document); Usage//Trigger File Upload event Myupload ({//upload File receive address Uploadurl: "/async/myupload.php",///select file, before sending file custom event//file for uploaded file information, can do file detection here, Initialize progress bar action Beforesend:function (file) {},///////////////////////////////////////////////////////////res Take a look at res, where you can add the progress bar related code uploading:function (res) {}});

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.