在node.js服务器上接受请求正文中的二进制文件 [英] Accept binary file in body of request on a node.js server

查看:222
本文介绍了在node.js服务器上接受请求正文中的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在POST的主体中上传一个二进制文件.

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

我不想使用multipart/form-data.

(据我所知,multipart/form-data是一种适用于Web应用程序的易于使用的技术,但不适用于移动应用程序.我没有Web应用程序,我只是在构建移动应用程序.)

(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.)

我尝试使用busboy,但在非multipart/form-data上传中找不到任何内容. express-fileupload也使用相同的AFAIK.

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.

推荐答案

因此,如果我理解正确,则希望创建一个路由,该路由将用于将文件上传到服务器.一种方法是将body-parser表达式中间件与写流结合使用:

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'});
});

发送以下请求会将文件上传到[SERVER_UPLOAD_PATH]:

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.

这篇关于在node.js服务器上接受请求正文中的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆