最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Read blob file in base64 and upload on the server - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Apr 13, 2018 at 8:47 Ali Hesari asked Apr 12, 2018 at 18:02 Ali HesariAli Hesari 1,9495 gold badges27 silver badges54 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论