HTML 5 upload image file (including drag, preview, upload, beautification)


Welcome to Laker’s blog, the program of attack
Micro blog: jiangxiaohu Laker

HTML 5 upload image file (including drag, preview, upload, beautification)

The last article talked about how to upload files. This article talks about the details of image upload, preview and so on.

About interface

File API

  • File – a stand-alone file; provides read-only information such as name, file size, mimeType, and a reference to a file handle.

  • Filelist – a sequence of class arrays of file objects (consider uploading multiple files or dragging directories or files from the desktop).

  • Blob – file can be split into byte ranges.

  • FileReader – read file or blob

  • URL scheme

Check whether the browser supports

//Check whether the file API is supported
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // support
} else {
  Alert ('not supported ');

Basic code

Select a picture and preview:

<input id="img_input" type="file" accept="image/*"/>
<label for="img_input"></label>
<div class="preview_box"></div>

.preview_box img {
  width: 200px;

$("#img_input").on("change", function(e){

  Var file = [0]; // get image resources

  //Select only picture files
  if (!file.type.match('image.*')) {
    return false;

  var reader = new FileReader();

  Reader. Readasdataurl (file); // read the file

  //Render file
  reader.onload = function(arg) {

    var img = '<img class="preview"/>';

Upload to server

var form_data = new FormData();
var file_data = $("#img_input").prop("files")[0];

//Put the uploaded data into form data
form_data.append("user", "Mike");
form_data.append("img", file_data);

    Type: "post", // post is used to upload files
    url: "",
    dataType : "json",
    Crossdomain: true, // if cross domain is used, you need to enable CORS in the background
  Process data: false, // Note: do not process data
  Contenttype: false, // Note: do not set contenttype
    data: form_data
}).success(function(msg) {
}).fail(function(msg) {

Drag and drop uploads

Three related events:

  • dragenter

  • dragover

  • drop

Native javascript:


<div id="drop_zone">Drop files here</div>
<ul id="list"></ul>

//You must block the default behavior of the dragender and dragover events in order to trigger the drop event
function fileSelect(evt) {


  Var files = EVT. Datatransfer. Files; // file object
  var output = [];

  //Working with multiple files
  for (var i = 0, f; f = files[i]; i++) {
    output.push('<li><strong>', escape(, '</strong> (', f.type || 'n/a', ') - ',
                f.size, ' bytes, last modified: ',
                f.lastModifiedDate.toLocaleDateString(), '</li>');
  //Show file information
  document.getElementById('list').innerHTML = output.join('');

function dragOver(evt) {
  evt.dataTransfer.dropEffect = 'copy';

// listener
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', dragOver, false);
dropZone.addEventListener('drop', fileSelect, false);


Other codes can remain the same. When listening to events, due to the encapsulation of jQuery, the fields stored in the data are changed. The parameters aree.originalEventInstead ofe

$("#drop_zone").on('dragover', function(e){

$("#drop_zone").on('drop', function(e){

Beautify upload box

Method 1: call the click () method on the hidden file input box

Hide the default file input box<input>Element, using a custom interface to act as a button to open the file selection dialog box. To use stylesdisplay:noneHide the original file input box and call its click () method when necessary.

<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
< a href = "ා" id = "fileselect" > select a file</a>

var fileSelect = document.getElementById("fileSelect"),
  fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", function (e) {
  if (fileElem) {
    Fileelem. Click(); // you can use trigger() for jQuery
  e.preventDefault(); // prevent navigation to "#"
}, false);

Method 2: use label

Hide the input, write the style to the label, and click the label to operate the input.


<input id="img_input2" type="file" accept="image/*"/>
< label for = "img? Input2" id = "img? Label2" > select file
    <i class="fa fa-plus fa-lg"></i>
<div id="preview_box2"></div>

#img_input2 {
  display: none;
#img_label2 {
  background-color: #f2d547;
  border-radius: 5px;
  display: inline-block;
  padding: 10px;
#preview_box2 img {
  width: 200px;

Recommended Today

Python final review resources

Tip: blue is the required part, yellow is the prompt and unnecessary part. 1. Source code file extension * py 2. Python uses indentation as the syntax boundary, and generally uses four grid indentation. 3. Python variables and functions are defined without specifying the type.  Python variables do not need to be declared in advance […]