简体   繁体   中英

Simple async image upload for Express?

I'm using a button click to trigger a file input dialog. Once the file is selected, I'm displaying the thumbnail in a preview.

const uploadListener = function() {
  const preview = document.getElementById('preview')
  const uploadBlob = window.URL.createObjectURL(this.files[0])
  preview.style.backgroundImage = `url(${ uploadBlob })`;
}

const fileUploader = document.getElementById('fileUpload')
fileUploader.addEventListener('change', uploadListener)

From here, what's the easiest way to get the file at uploadBlob asynchronously sent (via XMLHttpRequest()?) to my node.js Express server and saved to the server?

I've written this out with a base64 encoded FileReader() in the past, where you have to filter out the metadata, then decode to a binary file and figure out the name + extension on the server, but it was slow and seemed sort of obscure.

It's misleading to name the variable uploadBlob since it's not a blob any more. it's a url, you don't send that to the server.

Basically, append the blob/file to a FormData , then send the formdata in your ajax request

const fd = new FormData()
fd.append('avatar', this.files[0])
// fd.append('avatar', this.files[0], optionalFileName)

fetch(uploadUrl, {method: 'post', body: fd})

/* 
or using XMLHttpRequest:

var xhr = new XMLHttpRequest
xhr.open('POST', uploadURL)
xhr.send(fd)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM