1

When I drop a file in the upload area, the React-dropzone returns an object such as:

let picture = [
    {
        "rawFile": {
            "preview": "blob:http://localhost:3000/ff851b03-b2c0-4212-9240-8d07057ad47d"
        },
        "src": "blob:http://localhost:3000/ff851b03-b2c0-4212-9240-8d07057ad47d",
        "title": "1397-01-20 13.43.24.jpg"
    }
]

I read this link and try to upload the file: React dropzone, how to upload image?

But I think the file will not be sent.

This is my code:

let formData = new FormData();
formData.append('file', picture[0]);
fetch('http://localhost:8000/api/media', {
 method: 'POST',
 body: formData
});

If this method is not correct, How to send the file to the server side and receive it on the server side?

On the server side, I'm using Hapij.

Ali Hesari
  • 1,821
  • 5
  • 25
  • 51

1 Answers1

3

I solved the problem. I write the answer because anybody didn't answer this question.

In the client side, I use the FileReader API to read the BLOB data and convert it to base64 readable format. I write a function to convert blob to base64 and send fileName and base64 to the server side.

const convertFileToBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file.rawFile);

    reader.onload = () => resolve({
        fileName: file.title,
        base64: reader.result
    });
    reader.onerror = reject;
});

On the server side, I write the buffer to the file by this function:

const fs = require("fs");
const Boom = require('boom');

function convertBase64ToFile(file) {

  let base64Data = file.base64.split(',')[1];

  fs.writeFile(`${__dirname}/../../uploads/${file.fileName}`, base64Data, 'base64', function(err) {
    return Boom.badData(err);
  });

  // Other actions...

}

This method works for me perfectly.

Ali Hesari
  • 1,821
  • 5
  • 25
  • 51
  • 1
    readAsDataURL only accept File or Blob how did you do that whitout exception?! https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Amin Rahimi Apr 13 '18 at 10:56
  • @AminRahimi I don't receive any exceptions. I read this link and rewrite code by promise: https://stackoverflow.com/questions/6926016/nodejs-saving-a-base64-encoded-image-to-disk – Ali Hesari Apr 13 '18 at 14:26
  • I don't know react-dropzone, but If this code works, then the one in the question must have worked too. Both methods expect a Blob as input. – Kaiido Apr 15 '18 at 05:55