Home Web Front-end JS Tutorial About js drag and drop upload [A process of drag and drop upload to modify avatar]_javascript skills

About js drag and drop upload [A process of drag and drop upload to modify avatar]_javascript skills

May 16, 2016 pm 06:04 PM
Drag and drop upload

Many modern browsers now support drag-and-drop file reading operations, and their advantages will not be repeated again. The front-end time used drag and drop to improve the avatar upload process of the website, and made a summary of the key points and practical experience.

Let’s take a look at the overall view first:

1. The file drag-and-drop acceptance area should be clearly marked and should be as large as possible (due to layout reasons, the drag-and-drop box of this interface is not Not big). You can use dashed box and other styles to attract users to drag and drop files. It is best to have obvious text prompts and icons.

2. In the interactive experience, when a file is dragged into the browser window, the drag and drop area can be used to change the background color, etc. to invite the user for a drop operation.
Implementation code:

Copy code The 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 more modern browsers such as IE9. Therefore, we must prepare ordinary file browsing and uploading as a backup solution for browsers that do not support drag and drop.
When drag-and-drop file reading is not supported, the interface is as follows:

The code to implement detection is as follows:

Copy code The code is as follows:

it.detectDragable = function(){
filedrag = !!window.FileReader;
if(!filedrag) return;
$("#avtcnt").addClass('dragable');

Processing when placing files:



When the file is placed in the acceptable area, please note that no matter whether the file you drag and drop on the mouse is single or multiple, the e.dataTransefer.files transferred between the browser and the operating system are always plural. That is, multiple files. This also means that you need to loop through the files carried by the mouse.
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; ivar file = files[i];
if(!file.type.match(/image*/)){
noimg ;
if(noimg ==files.length){
QSL.optTips('Please select jpg, png, gif Pictures in 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);

}

브라우저로 드래그한 파일 처리


stopdft(e)는 기본적으로 브라우저가 파일을 열지 못하도록 방지하는 것입니다. 대신 스크립트는 끌어서 놓은 파일을 처리합니다.
이 과정에서는 이미지 파일이 필요하므로 e.dataTransfer.files 객체를 조작하여 이미지 유형의 파일을 찾는 것이 편리합니다.
그렇지 않은 경우 메시지가 표시됩니다.

파일 읽기를 위한 키 코드:
var reader = new FileReader();


reader.onload = function(e){
var img = document. ('img');
img.src = reader.result;
reader.readAsDataURL(file)
이 예에서는 이미지의 높이 및 너비 속성을 읽어야 합니다. . 그래서 우리는 다음 작업을 수행했습니다.
setTimeout(function(){
it.imgSize = {
w:img.width,
h:img.height
};
}, 500);
로컬 파일을 읽는 중이지만 이미지가 실제로 읽히는지 확인하는 데 여전히 지연이 있습니다. 그렇지 않으면 일부 브라우저에서는 너비와 높이 값을 얻지 못할 수 있습니다. (다른 쉬운 방법이 있나요? 지적해주세요)

기존 이미지 삭제 및 드래그 영역 재설정:
로컬 이미지를 탐색하고 읽은 후 사용자에게 삭제 및 재설정 옵션을 제공합니다. (물론 직접 올리는 것이 더 쉽습니다)

코드 복사 코드는 다음과 같습니다.
it.resetDropbox = function(){
dropbox.attr("class","dropbox")
.empty()
.text("이 영역으로 파일을 드래그하세요.")
imgData = '' ;
it.imgData = '';
it.imgSize = {w:0,h:0}
picsub.removeClass("업로드 중")
.find("버튼 ").removeAttr("disabled")
.text("Upload");
imagedata.val('');
clearner.hide();

재설정 드래그 영역


파일을 읽기 위해 드래그 앤 드롭하는 과정은 기본적으로 여기에서 완료됩니다.
끌어서 놓기를 사용하여 로컬 파일을 읽을 때의 다른 장점:
사진 업로드 및 변경의 일반적인 프로세스는 다음과 같습니다. 사진 선택 - 사진 업로드 - 성공적으로 업로드 - 서버가 사진 클라이언트 검색 효과를 반환합니다.
그리고 드래그 앤 드롭을 사용하면 로컬 파일을 읽는 경우 서버에서 사진을 반환하는 단계를 저장하고 reader.result에서 반환된 데이터를 직접 사용할 수 있습니다.
이렇게 하면 서버에서 이미지를 읽는 데 따른 지연이 줄어들고 왕복 데이터 트래픽이 절약됩니다. 따라서 서버측 이미지가 성공적으로 업로드되었고 이미지 미리보기가 로컬 데이터를 검색하는지 확인하세요.
코드:

코드 복사 코드는 다음과 같습니다.
function initImageCrop(url){
var t = document.getElementById("target"),
p = document.getElementById("preview") ,
b = browserImage,
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;


이미지 업로드 성공 후 처리


전체 DEMO 미리보기
(정적 파일은 업로드 성공 후 표시되지 않습니다. (:)데모 스크립트
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles