About JS drag and drop upload [a drag-and-drop upload modified avatar process]_javascript Tips

Source: Internet
Author: User

Modern browsers already have a lot of support for drag-and-drop file reads, and their advantages are no longer repeated. Front-end time use drag and drop to improve the site's avatar upload process, the main points and practical experience to do a little summary.

Let's take a look at the overall view:

1, the file drag-and-drop accept the area to have a clear indication, and to be as large as possible (because of the layout of the reason, the interface of the drag-and-drop box is not large). You can use styles such as dotted box boxes to attract users to drag and drop files. It is best to have obvious text hints and icons to match.

2, in the interactive experience files dragged into the browser window, you can use the drop area to change the background color to the user to initiate placement operation invitation.
Implementation code:

Copy Code code as follows:

Doc.bind ({
' DragEnter ': function (e) {
$ ("#brsbox"). AddClass ("Dragbrowse");
Dropbox.addclass ("Shine");
return false;
},
' DragLeave ': function (e) {
Dropbox.removeclass ("Shine");
return false;
},
' Drop ': function (e) {
STOPDFT (e);}
});
Dropbox.bind ({
' DragEnter ': function (e) {
Dropbox.addclass ("Candrop");
STOPDFT (e);},
' DragLeave ': function (e) {
Dropbox.removeclass ("Candrop");
STOPDFT (e);},
' DragOver ': function (e) {
STOPDFT (e);},
' Drop ': function (e) {

}

For browsers that do not support dragging:

Unfortunately, some browsers do not support file drag-and-drop reading, which includes more modern browsers such as IE9. So we have to prepare normal file browsing uploads for browsers that do not support drag and drop as a fallback option.
When drag-and-drop file reads are not supported, the interface is as follows:

The code to implement instrumentation is as follows:

Copy Code code as follows:

it.detectdragable = function () {
Filedrag =!! Window. FileReader;
if (!filedrag) return;
$ ("#avtcnt"). AddClass (' dragable ');

Processing of files when placed:



When a file is placed in an acceptable area, be aware that the e.datatransefer.files that is transmitted between the browser and the operating system is always plural, whether the file you drag on the mouse is single or multiple. which is multiple files. This means that you need to loop through the files that you carry on your mouse.
The code is as follows:

Copy Code code as follows:

Dropdom.addeventlistener (' Drop ', function (e) {
It.handlefile (E.datatransfer.files);
STOPDFT (e);},false);

};

It.handlefile = function (files) {
var noimg = 0;
for (var i=0; i<files.length; i++) {
var file = Files[i];
if (!file.type.match (/image*/)) {
Noimg + +;
if (noimg ==files.length) {
Qsl.opttips (' Please select JPG, PNG, GIF, etc. in the format of the picture ');
return false;
}
Continue
}

var reader = new FileReader ();
Reader.onload = function (e) {
var img = document.createelement (' img ');
IMG.SRC = Reader.result;
settimeout (function () {
It.imgsize = {
W:img.width,
H:img.height
};
},500);
Dropdom.innerhtml= "";
Img.classname = ' localimg ';
It.imgdata = Reader.result;
Dropdom.appendchild (IMG);
Imagedata.empty (). Val (Reader.result);
Dropbox.addclass ("droped");
Clearner.show ();
};
Reader.readasdataurl (file);

}

Handling files dragged to the browser


where STOPDFT (e) is to prevent the browser from operating by default and not to open the file in a browser. Instead, the script handles the dragged file.
In this process, we need a picture file, so it is convenient to manipulate the E.datatransfer.files object and look for files of type image.
If not, you will be prompted.

Key code to read files:
var reader = new FileReader ();


Reader.onload = function (e) {
var img = document.createelement (' img ');
IMG.SRC = Reader.result;
};
Reader.readasdataurl (file);
In this case we need to read the height and width properties of the picture. So we did the following things
settimeout (function () {
It.imgsize = {
W:img.width,
H:img.height
};
},500);
Although it is a local file read, it still has to be delayed to ensure that the picture is actually read. Otherwise, you will not get a wide-high value in some browsers. (Can there be any other simpler way?) I hope to point out)

Delete an existing picture and reset the drag area:
After browsing the local picture, provide the user with the option to delete and reset. (It's easier if you upload it directly)
Copy Code code as follows:

It.resetdropbox = function () {
Dropbox.attr ("Class", "Dropbox")
. Empty ()
. text (Drag the file to the area);
Imgdata = ';
It.imgdata = ';
It.imgsize = {w:0,h:0};
Picsub.removeclass ("uploading")
. Find ("button"). Removeattr ("Disabled")
. Text ("Upload");
Imagedata.val (");
Clearner.hide ();

Reset Drag Area


Here, drag and drop the process of reading a file basically ends.
Use drag-and-drop to read other benefits of local files:
The normal upload change picture process is: Select picture-upload picture-upload Success-server return picture-client browsing effect
If you use drag-and-drop to read a local file, you can save the server from returning the picture, using the data returned directly by Reader.result.
This saves the latency of reading pictures from the server and saves round-trip data traffic. So just make sure that the server-side image upload is successful, and the picture preview will fetch the local data:
Code:
Copy Code code as follows:

function Initimagecrop (URL) {
var t = document.getElementById ("target"),
p = document.getElementById ("preview"),
b = Browseimage,
s = [],
ts = [];
if (url== ' data ') {
T.SRC = B.imgdata;
P.SRC = B.imgdata;
Posimage (b.imgsize.w,b.imgsize.h);
}else{
var cutimg = new Image ();
Cutimg.onload = function () {
t.src = URL;
p.src = URL;
Posimage (Cutimg.width,cutimg.height);
}
cutimg.src = URL;

Image upload success after the processing

Full Demo preview (static file is temporarily not uploaded after successful display (:)
Demo Script

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.