gpt4 book ai didi

node.js - 如何从koa2中的多部分数据解析流

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:40 31 4
gpt4 key购买 nike

所以我在多部分表单数据中上传流数据

var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
const request = require('request');

var FormData = require('form-data');

var formData = {
my_field: 'my_value',
my_file: fs.createReadStream('robot.jpg'),
};

request.post({url:'http://localhost:3456/fileStorage', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});

在服务器端我尝试了 koa-multer,在尝试访问文件时出现错误。只需使用普通的 koa-body,我可以看到文件已上传,但无法将其保存回文件,有任何提示吗?

{ my_file: 
File {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
size: 15562,
path: '/var/folders/l6/lmwkwk196_qfxxngv5ys0lp00000gn/T/upload_fc48a19e6ee5abf8a9a361d784725b78',
name: 'robot.jpg',
type: 'image/jpeg',
...
}

来源是这个

var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
//const multiparty = require('multiparty');
//const multer = require('koa-multer');
var app = new Koa();
var router = new Router();
//const upload=multer({desk: './uploads/' });

router
.post(`/upload`, koaBody({multipart:true}),
(ctx) => {
console.log('----- hello ----');
console.log(ctx.request.body.files);
console.error('---------------');
const writeStream = fs.createWriteStream('./111.jpg');
ctx.request.body.files.my_file.pipe(writeStream);
});
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3456);

最佳答案

好的,我刚刚这样做了const readStream = fs.createReadStream(ctx.request.body.files.my_file.path);

这样我就可以从http post接收多部分中的文件流。

关于node.js - 如何从koa2中的多部分数据解析流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396795/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com