About js drag-and-drop upload [a drag-and-drop upload process for modifying an avatar]

Source: Internet
Author: User

Nowadays, modern browsers support reading drag-and-drop files, and their advantages are not repeated. The front-end time uses drag-and-drop operations to improve the website's profile picture upload process and summarize the key points and practical experiences.

First look at the overall view:

1. The drag and drop area of the file must be clearly marked and as big as possible (because of the layout, the drag and drop box on the interface is not large ). You can drag files with dotted box or other styles. It is best to have obvious text prompts and icons in combination.

2. When a file is dragged into the browser window in the interactive experience, you can use the drag-and-drop area to change the background color and initiate an invitation to place the file to the user.
Implementation Code:
Copy codeThe Code is 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 Drag and Drop:

Unfortunately, some Browsers Do not support drag-and-drop reading of files, including modern browsers such as IE9. Therefore, we must prepare a normal file browsing and uploading scheme for browsers that do not support drag and drop operations.
When reading drag-and-drop files is not supported, the interface is as follows:

 

The code for detection is as follows:
Copy codeThe Code is as follows:
It. detectDragable = function (){
Filedrag = !! Window. FileReader;
If (! Filedrag) return;
$ ("# Avtcnt"). addClass ('dragable ');

Processing of file placement:

 

 

When placing files in an acceptable area, note that no matter whether the files you drag and drop on the mouse are single or multiple,E. dataTransefer. files transmitted between the browser and the operating system are always plural. That is, multiple files. This means that you need to process the files carried by the mouse cyclically.
The Code is as follows:
Copy codeThe Code is 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 ('select images in jpg, png, gif, and other formats ');
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 );

}

Process the files dragged to the browser


Stopdft (e) is used to prevent default operations on the browser and does not open files in the browser. The script is used to process drag-and-drop files.
In this process, we need image files, so we can conveniently operate the e. dataTransfer. files object and find the files whose type is image.
If no, a message is displayed.

Key code for reading files:
Var reader = new FileReader ();


Reader. onload = function (e ){
Var img = document. createElement ('img ');
Img. src = reader. result;
};
Reader. readAsDataURL (file );
In this example, we need to read the image height and width attributes. So we did the following:
SetTimeout (function (){
It. imgSize = {
W: img. width,
H: img. height
};
},500 );
Although it is a local file reading, it still needs to be delayed to ensure that the image reading is complete. Otherwise, some browsers cannot obtain the value of the width or height. (Are there other simpler methods? Hope to point out)

Delete an existing image and reset the drag and drop area:
After reading the local image, you must provide the options for deleting and resetting the image. (For direct upload, it is easier)
Copy codeThe Code is as follows:
It. resetDropbox = function (){
Dropbox. attr ("class", "dropbox ")
. Empty ()
. Text ("drag a file to this region ");
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, the process of dragging and dropping to read files is basically over.
Other advantages of using drag and drop to read local files:
The general process for uploading and changing images is: Select image> upload success> server return image> client browsing Effect
If you use drag and drop to read a local file, you can skip the steps for the server to return an image and directly use the data returned by reader. result.
In this way, the delay in reading images from the server is reduced, and the round-trip data traffic is reduced. Therefore, you only need to confirm that the image on the server is successfully uploaded, and preview the image to retrieve the local data:
Code:
Copy codeThe Code is 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;

Processing of images uploaded successfully

Complete DEMO Preview (static files are not displayed after being uploaded successfully (:)
DEMO script

Related Article

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.