Home > Web Front-end > H5 Tutorial > body text

Implement image upload and preview functions through html5

PHPz
Release: 2017-03-12 09:16:50
Original
2061 people have browsed it

Recently, I need to use the image upload and preview functions for my projects. Since it is for mobile phones, I studied the implementation of H5.

Picture preview

First, solve the problem of picture preview. In html5, FileReader is provided to read local files, allowing us to implement the image preview function.

FileReader

  • Properties, all properties are read-only:

    • FileReader.error, DOMError that occurs when reading file .

    • FileReader.readyState, reading status; 0, no data is loaded; 1, data is loading; 2, reading has been completed.

    • FileReader.result, file content; this property is only valid after the read operation is completed, and the format depends on the method used when reading.

  • Event :

    • FileReader.onabort, read operation aborted.

    • FileReader.onerror, an error occurred while reading.

    • FileReader.onload, after the read has completed successfully.

    • FileReader.onloadstart, reading starts.

    • FileReader.onloadend, the reading is completed, regardless of whether the reading is successful or not.

    • FileReader.onprogress, when reading the Blob content.

  • Method:

    • FileReader.abort()
      Abort reading. Then readyState becomes 2.

    • FileReader.readAsArrayBuffer()
      Read the file into ArrayBuffer.

    • FileReader.readAsBinaryString()
      Read into a binary string.

    • FileReader.readAsDataURL()
      Read as DataURL.

    • FileReader.readAsText()
      Read as text.

  • Browser compatibility is shown in the figure:
    Implement image upload and preview functions through html5
    Implement image upload and preview functions through html5

##Preview Function implementation

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>图片上传预览</title><script type="text/javascript">
    function imgPreview(fileDom){
        //判断是否支持FileReader
        if (window.FileReader) {            var reader = new FileReader();
        } else {
            alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
        }        //获取文件
        var file = fileDom.files[0];        var imageType = /^image\//;        //是否是图片
        if (!imageType.test(file.type)) {
            alert("请选择图片!");            return;
        }        //读取完成
        reader.onload = function(e) {
            //获取图片dom
            var img = document.getElementById("preview");            //图片路径设置为读取的图片
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }</script></head><body>
    <img  id="preview" / alt="Implement image upload and preview functions through html5" >
    <br />
    <input type="file" name="file" onchange="imgPreview(this)" /></body></html>
Copy after login

Effect preview:


Implement image upload and preview functions through html5

Upload function

function upload() {
        var xhr = new XMLHttpRequest();        var progress = document.getElementById("progress")
        progress.style.display = "block";

        xhr.upload.addEventListener("progress", function(e) {
            if (e.lengthComputable) {                var percentage = Math.round((e.loaded * 100) / e.total);
                progress.value = percentage;
            }
        }, false);

        xhr.upload.addEventListener("load", function(e){
              console.log("上传完毕...")
          }, false);

        xhr.open("POST", "upload");
        xhr.overrideMimeType(&#39;text/plain; charset=x-user-defined-binary&#39;);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText); // handle response.
                progress.style.display = "none";
                progress.value = 0;
            }
        };        var file = document.getElementById("imgFile");        var fd = new FormData();
        fd.append(file.files[0].name, file.files[0]);
        xhr.send(fd);
    }
Copy after login

The above is the detailed content of Implement image upload and preview functions through html5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template