简体   繁体   中英

Accept binary file in body of request on a node.js server

I want to upload a binary file in the body of a POST .

I do NOT want to use a multipart/form-data .

(As far as I know multipart/form-data is an easy to use technology for web apps, but not easy for mobile apps. I don't have a web app, I'm just building mobile apps.)

I've tried using busboy, but haven't been able to find anything on non multipart/form-data uploads. express-fileupload also uses the same thing AFAIK.

So if I understand correctly, you want to create a route that will be used to upload files to the server. One way to do this is by using the body-parser express middleware combined with a write stream:

const bodyparser = require('body-parser');
const express = require('express');
const fs = require('fs');
const app = express();

app.post('/upload/:image', bodyparser.raw({
    limit: '10mb', 
    type: 'image/*'
}), (req, res) => {
    const image = req.params.image;
    const fd = fs.createWriteStream(`[SERVER_UPLOAD_PATH]/${image}`, {
        flags: "w+",
        encoding: "binary"
    });
    fd.end(req.body);
    fd.on('close', () => res.send({status: 'OK'});
});

Sending the following request will upload the file to the [SERVER_UPLOAD_PATH]:

curl -X POST -H 'Content-Type: image/png' --data-binary @[image-path]/image.png http://[server-url]/upload/image.png

The above example is used to upload images to the server but you can modify it accordingly. Note that you will need to check for the file type to make sure that the users are uploading only the file types that they are supposed to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM