Convert File type to Data URI - React-Dropzone

2019-06-28 01:41发布

问题:

I am having trouble integrating React-dropzone with FeathersJS Upload

I have successfully implemented the RESTful upload when you POST a datauri to my Upload endpoint. { uri: data:image/gif;base64,........}

My issue is when selecting a file in react-dropzone and submitting the form, I am seeing a File type... It seem's I need to somehow convert that to a data URI.

This should be handled by Dauria... But I think my issue is in my POST request, not having the file property set with the correct file format. Should I be converting the File to FormData?

回答1:

Here is one way to do it from File object:

Using Image and FileReader allows you to get width, height and base64 data:

onDrop = (acceptedFiles, rejectedFiles) => {
  const file = acceptedFiles.find(f => f)
  const i = new Image()

  i.onload = () => {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      console.log({
        src: file.preview,
        width: i.width,
        height: i.height,
        data: reader.result
      })
    }
  }
  
  i.src = file.preview
}