Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

html - Show an image preview before upload

In my HTML form I have input filed with type file for example :

 <input type="file" multiple>

Then I'm selecting multiple files by clicking that input button. Now I want to show preview of selected images before submitting form . How to do that in HTML 5?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:

The html code:

<input accept="image/*" type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById('files').onchange = function () {
  var src = URL.createObjectURL(this.files[0])
  document.getElementById('image').src = src
}

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

function handleFileSelect (evt) {
  // Loop through the FileList and render image files as thumbnails.
  for (const file of evt.target.files) {
 
    // Render thumbnail.
    const span = document.createElement('span')
    const src = URL.createObjectURL(file)
    span.innerHTML = 
      `<img style="height: 75px; border: 1px solid #000; margin: 5px"` + 
      `src="${src}" title="${escape(file.name)}">`

    document.getElementById('list').insertBefore(span, null)
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...