Local upload, preview in advance (image, video)
The div tag Preview in 1.html shows that the button tag triggers the upload event.
<div id= "Drop_area" style= "border:3px dashed silver;width:200px; height:200px" > Dragging a picture to this </div>< Button onclick= "XHR2 ()" >ajax upload </button>
2. Disable browser Open file behavior
Document.addeventlistener ("Drop", function (e) { //Drag off E.preventdefault (); }) Document.addeventlistener ("DragLeave", function (e) { //drag-and-drop E.preventdefault (); }) Document.addeventlistener ("DragEnter", function (e) { //drag into E.preventdefault (); }) Document.addeventlistener ("DragOver", function (e) { //Drag to drag e.preventdefault (); })
3. Drag and drop to preview the file
var box = document.getElementById (' Drop_area '); Drag area Box.addeventlistener ("Drop", function (e) {var fileList = e.datatransfer.files;//Get File object//Check if it is a drag-and-drop file-to-page operation if (Filelist.length = = 0) {return false; }//Drag the image to the browser to enable preview function//required video format Array.prototype.s=string.fromcharcode (2); Array.prototype.in_array=function (e) {var r=new RegExp (this. S+e+this. S); return (R.test (this. S+this.join (this. S) +this. S));}; var video_type=["Video/mp4", "Video/ogg"];//create a URL connection for the Src attribute to refer to var fileurl = window. Url.createobjecturl (Filelist[0]); if (Filelist[0].type.indexof (' image ') = = = 0) {//assumed to be picture var str= " ";d ocument.getelementbyid (' Drop_area '). Innerhtml=str; }else if (Video_type.in_array (Filelist[0].type)) {//assumes the video in the specified format var str= "<video width= ' 200px ' height= ' 200px ' controls= ' controls ' src= ' "+fileurl+" ></video> ";d Ocument.getelementbyid (' Drop_area '). innerhtml= Str }else{//Other format, output fileName//alert ("no preview"), var str= "file name Word:" +filelist[0].name;document.getelementbyid (' Drop_area '). Innerhtml=str; }resultfile = Filelist[0];},false);
4.ajax Upload
function xhr2 () {var xhr = new XMLHttpRequest ();//First step//New FormData object var formData = new FormData ();//++++++++++// Append file Data formdata.append (' file ', resultfile);//post mode Xhr.open (' POST ', ' xhr2.php '); Second step//Send request Xhr.send (formData); The third step//ajax returns Xhr.onreadystatechange = function () {//Fourth step if (xhr.readystate = = 4 && xhr.status = = 200) { Console.log (Xhr.responsetext); }};//Set timeout time xhr.timeout = 10000;xhr.ontimeout = function (event) {alert (' Request timed out! '); }}
5.php Save File
<?phpprint_r ($_files["file"]), $name = $_files["File" ["Name"]; Chinese may be garbled using the Iconv function move_uploaded_file ($_files["file"] ["Tmp_name"],iconv ("UTF-8", "gb2312", $name));>
JavaScript Implementation Drag-and-drop preview, Ajax small file upload