File talk--drag and drop asynchronous upload implementation

Source: Internet
Author: User
Tags sendfile

In the previous article, "File talk-drag-and-drop upload," I made a static drag-and-drop upload interface, drag-and-drop files to the display area release, you can display the basic information dragged into the file. This article will be further processed on this basis to create a complete drag-and-drop upload example.

Example description

The file upload function is triggered by clicking the area selection file or by dragging the file directly into the area, and the files are sent asynchronously to the server. After the service end processing is completed, the basic information is returned and displayed on the page. Because of the server capacity problem, this example does not do file saving processing, just simple to return the file basic information, file upload back-end specific processing logic needs to be self-supplementing.

The new little partner Formdata

We know that the traditional file upload if you want to achieve asynchronous effect, we will use the IFRAME to simulate, or use flash upload plugin. But today, we met a new member,--fromdata, which can create form objects from JS and add form data (strings, numbers, files, and so on) to the object. Combining our familiar XMLHttpRequest objects, we submit the form data to the server asynchronously, so our problem is solved.

Below, let's look at the core code:

  function UploadFile (fs) {var len = fs.length;    for (var i = 0; i < len; i++) {sendFile (fs[i]);    }}function sendFile (file) {var xhr = new XMLHttpRequest (), FD = new FormData ();    Fd.append (' file ', file); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && xhr.status = = 200) {//Outputs the service-side return information to the log area (consider multiple        case) consolediv.innerhtml + = ' <br> ' + xhr.responsetext;    }    };    Xhr.open (' POST ', './upload.php '); Xhr.send (FD);} When the file control changes, call the UploadFile function, triggering the upload function File.onchange = function () {uploadfile (this.files);};/    /Call File Upload function Area.ondrop = function (EV) {Ev.preventdefault () when releasing drag-in files within a zone;    var dt = Ev.datatransfer; UploadFile (dt.files);};  

The code is simple and does not have much elaboration. But here I would like to make a personal comment: According to the example, it is not difficult to find that there is a problem-if users use the drag-and-drop upload function, instead of using the click-Trigger file control to select files to upload, then file control does not exist at all necessary. In connection with the view that the status of the file control I mentioned above is threatened, I am bold to assume that if a future standard gives each htmlelement a functional interface for selecting a file, then the drag-and-drop function can be set above an element, By then, the status of file control is probably not only threatened, it is likely to exit the historical stage! Because of the file control visual effect and the interaction is not uniform angle to consider, I think the above speculation is still possible, haha ~ ~

Although the example does not do much work on the backend, I will use PHP as an example to illustrate how the backend should work. For example, my code is like this:

$file = $_FILES[‘file‘];echo json_encode($file);

Can be said to be very simple. And we often involve more and more complex processing logic in the actual application. At the very least, we should move the tmp_name corresponding temporary files to our designated upload directory. Of course, this process we will judge the file type, size limit, rename, data preservation, and so on. Basic code:

$file = $_FILES[‘file‘];$path = ‘./upload‘;if ($file[‘size‘] > 2000000) {    echo ‘{"error": "1000", "message": "上传文件大小超限,不能超过xxM"}‘;}$path .= ‘/file_‘ . time() . ‘.png‘;// 这里还可能会存在文件数据保存,新旧名称关联等逻辑move_uploaded_file($file[‘tmp_name‘], $path);
A magical way to sendasbinary

We talked about the use of Formdata to implement asynchronous file upload, in the high-level browser can work properly, there is no problem. Next we have another way to implement asynchronous uploads in Firefox. This way, we will make a new friend--firereader. FileReader is a new object in HTML5 that can access the user's local files and can read the contents of the file in different formats.

FileReader Basic Use

First, let's look at how to create an FileReader instance object and what instance methods it has. Creating a FileReader object in JS is simple:

var reader = new FileReader();

We can access the local files through the reader object, so what properties, events, and methods are common to the reader object? Take a look at the following list:

Event
    • onload: Triggered when a file is successfully read
    • onloadend: triggered when the file is read, whether successful or not
    • onloadstart: Triggers when a file is started to read
    • onprogress: In file read, commonly used to get read progress
    • onabort: File read operation interrupted
    • onerror: File Read error
Property
    • result: Read the contents of the file, when the read operation is complete after the effective
    • readyState: FileReader the current state of the object
    • error: Error message On Error
Method
    • abort: Interrupt File Read operation
    • readAsBinaryString: Reads the contents of the file into binary format
    • readAsDataURL: Reads the contents of the file into the Dataurl format, commonly referred to as the Base64 format
    • readAsText: Reads the contents of the file as text

The above is the most common content of FileReader objects, let's look at a small example:

var rd = new FileReader();rd.onload = function(ev) {    console.log(ev.target.result);};rd.readAsText(file);

The file parameter in the above code is a file object that can be filelist in the Files property of the file control, or it can be one of the filelist in the Files property in DataTransfer.

FileReader + sendasbinary for asynchronous uploads

Met Firereader, let's look at how to use the FileReader and XMLHttpRequest Sendasbinary method in Firefox to implement asynchronous file upload. The core code is as follows:

function sendByBinary(file) {    var xhr = new XMLHttpRequest(),        reader = new FileReader();    xhr.onreadystatechange = function() {        if (xhr.readyState == 4 && xhr.status == 200) {            consoleDiv.innerHTML += ‘<br>‘ + xhr.responseText;        }    };    xhr.overrideMimeType(‘text/plain; charset=x-user-defined-binary‘);    xhr.open(‘POST‘, ‘./upload.php‘);    reader.onload = function(ev) {// 将二进制内容发送至服务端        xhr.sendAsBinary(ev.target.result);    };// 将文件内容读取为二进制格式    reader.readAsBinaryString(file);}

The code is simple, similar to Formdata's, and we'll look at how the server will get the Post's past file content (in PHP, for example):

// 方法一,这个方法需要php.ini开启支持$content = $GLOBALS[‘HTTP_RAW_POST_DATA‘];// 方法二,不需要php.ini设置,内存压力小$content = file_get_contents(‘php://input‘);

Therefore, the method of combining insurance is more comprehensive:

$content = $GLOBALS[‘HTTP_RAW_POST_DATA‘];if (empty($content)) {    $content = file_get_contents(‘php://input‘);}echo $content; // 输出文件内容

We're not talking about sendasbinary. This approach is currently only supported by Firefox, it is obvious how to deal with the file content from the server, this method obviously does not have the advantage of using Formdata way. Because the server only gets the file content and does not have information such as file type and size, it is unfriendly to the implementation of some restricted logic and file storage.

Author blog: Hundred Yards villa

File talk--drag and drop asynchronous upload implementation

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.