Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React dropzone, how to upload image?

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 }) 
like image 806
Yu Mad Avatar asked Dec 07 '16 18:12

Yu Mad


1 Answers

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); 
like image 131
George Borunov Avatar answered Sep 27 '22 22:09

George Borunov