29

Using React dropzone, I've successfully accessed the image using the onDrop callback. However, I'm trying to upload to Amazon S3 by sending the image to my server, saving to an S3 bucket, and returning a signed url to the image back to the client.

I can't do this with the information I have so far and the docs don't seem to mention this to my knowledge.

onDrop triggers a function call in my redux actions with the files:

export function saveImageToS3 (files, user) {
  file = files[0]
  // file.name -> filename.png
  // file -> the entire file object
  // filepreview -> blob:http:localhost:3000/1ds3-sdfw2-23as2

  return {
    [CALL_API] : {
      method:'post',
      path: '/api/image',
      successType: A.SAVE_IMAGE,
      body: {
        name: file.name,
        file: file,
        preview: file.preview,
        username: user
      }
    }
  }
}

However, when I get to my server, I'm not sure how to save this blob image (that's only referenced from the browser.)

 server.post('/api/image', (req, res) => {
  // req.body.preview --> blob:http://localhost:3000/1ds3-sdfw2-23as2
  // req.body.file -> {preview:blob:http://localhost:3000/1ds3-sdfw2-23as2}, no other properties for some reason
})
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Yu Mad
  • 828
  • 2
  • 12
  • 29
  • It looks like you're uploading the blob's URL rather than the bytes of the blob. You'd need to read the blob in using a FileReader/ArrayBuffer to get the bytes - lots of sample code out there on how to do that. But when I searched a bit, I found this, maybe it could help you: https://www.npmjs.com/package/react-dropzone-s3-uploader – Jeff McCloud Dec 07 '16 at 19:03
  • for anyone else - i also had to use multer server-side since it didn't register multipart form data. i used the below suggestions with new FormData to create the object, and then used multer in node as app.post('/api/image', upload.single('file'), function (){...}) to take care of it. – Yu Mad Dec 07 '16 at 20:40

1 Answers1

39

React Dropzone returns an array of File objects which can be sent to a server with a multi-part request. Depend on the library you use it can be done differently.

Using Fetch API it looks as follows:

var formData = new FormData();
formData.append('file', files[0]);

fetch('http://server.com/api/upload', {
  method: 'POST',
  body: formData
})

Using Superagent you would do something like:

 var req = request.post('/api/upload');
 req.attach(file.name, files[0]);
 req.end(callback);
George Borunov
  • 1,562
  • 1
  • 15
  • 14
  • 2
    @AlexYong You can use https://react-dropzone-uploader.js.org (full disclosure: I wrote it). react-dropzone doesn't help out with file uploads. If you want upload progress you have to use the XMLHttpRequest API (fetch doesn't provide upload progress), then write your own file preview. This is a pain, but RDU takes care of it for you. – kylebebak Jan 16 '19 at 06:53