DEV Community

Cover image for How to preview image before upload to server
mixbo
mixbo

Posted on

How to preview image before upload to server

Recently my team have case to upload image to server i just want to show progress to user image upload status. if show the user which image file upload is more graceful. so i just preview image and show the progress same time.

Alt Text

Look at the screenshoot. before the image show the upload icons. direction current image uploading to server. i thinks it's more simple and useful.

// html code
<input id="input_file" type="file" multiple @change="fileChange" />

// here file agrument from html input file tag
covertInputImageToDataURL(file) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader()
    fr.onload = () => {
      resolve(fr.result)
    }
    fr.readAsDataURL(file)
  })
}

// event listener to input file tag 
const files = []
fileChange() {
  const newFiles = document.getElementById('input_file')

  // covert all file to dataURL
  for (let i = 0; i < newFiles.length; i++) {
    const file = newFiles.item(i)
    const fileID = randomString() // random file id 
    const dataURL = await this.covertInputImageToDataURL(file)
        files[fileID] = { file, dataURL }
  }
} 
Enter fullscreen mode Exit fullscreen mode

Here is Vue.js Template Define

// use files 
<div v-for="key in Object.keys(files)" :key="key" >
  <img :src="files[key]['dataURL']" :alt="key" />
</div>
Enter fullscreen mode Exit fullscreen mode

So far we just listener input file tag file change event and covert files to dataURL. when we set img src attribute with dataURL the image will shown by the tag. we can know which image uploading.

Help it can help you :)

Top comments (0)