Uploading FileReader.readAsDataURL to express.js

I have the following code to upload to my Node.js / Express.js server.

var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { var result = http.post('/files', e.target.result); result.success(function () { alert('done'): }); } 

My route is as follows:

 app.post('/files', function (req, res) { var cws = fs.createWriteStream(__dirname + '/media/file'); req.pipe(cws); res.send('success'); }); 

When I open / media / file with a graphical application, I get a warning that it cannot read it. When I open the image file with a text editor, I see a base64 encoded string inside. Do I need to convert the string first before writing it to the table?

+4
source share
1 answer

The problem was that DataURL is being added with metadata. First you need to remove this part before creating the base64 buffer.

 var data_url = req.body.file; var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/); var ext = matches[1]; var base64_data = matches[2]; var buffer = new Buffer(base64_data, 'base64'); fs.writeFile(__dirname + '/media/file', buffer, function (err) { res.send('success'); }); 

Got most of the code from question .

+6
source

Source: https://habr.com/ru/post/1442059/


All Articles