我希望我的Web服务器有一个POSTed文件,然后将它转发给另一个服务器的POST请求。
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var JSON = require('JSON');
var https = require('https');
var fs = require('fs');
var request = require('request');
var upload = multer({ dest: 'uploads/' });
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // We are OK with self-signed
var serverURL = 'https://ec2-54-202-139-197.us-west-2.compute.amazonaws.com:443';
var app = express();
var parser = bodyParser.raw();
var result = null;
app.use(parser);
app.set('view engine', 'pug');
app.get('/',upload.single('avatar'), function (req, res) {
return res.render('index.pug', {results: [], result_pics: {}});
});
app.post('/makeRequest*', upload.single('uploadPicture'), function(req, res) {
console.log("Files:");
console.log(req.file);
console.log(req.body);
var r = request.post({url: serverURL, headers: {'User-Agent': 'Client Webserver'}}, function (err, httpResponse, body) {
console.log('got response');
console.log(err);
console.log(body);
body = JSON.parse(body);
content = body['content'];
console.log(content);
message_type = body.message_type;
result_pics = [];
result = [];
if (message_type == "error") {
result = ["ERROR: " + body.content];
}
else if (message_type == "student created") {
result = ["Student created."];
}
else if (message_type == "student deleted") {
result = ["Student deleted."]
}
else if (message_type == "picture inserted") {
result = ["Picture inserted."];
}
else if (message_type == "viewed pictures") {
pics = body.pictures;
for (key in pics) {
result_pics.push(cloudinary.image(pics[key], {width: 300, height: 200, crop: "crop"}));
}
}
else if (message_type == "listing information") {
student_table = body.content["student_table"];
student_to_pic_table = body.content["student_to_pic_table"];
for (i in student_table) {
student = student_table[i];
result.push("Student ID: " + student["student_id"] + " Nickname: " + student["nickname"]);
}
for (i in student_to_pic_table) {
student_pic = student_to_pic_table[i];
result.push("Student ID: " + student_pic["student_id"] + " Pic ID: " + student_pic["image_id"]);
}
}
else {
result = ["ERROR: returned message is not of valid type"];
}
res.render('index.pug', {results: result, result_pics: result_pics});
res.end();
});
var form = r.form();
if (req.file) {
form.append('uploadPicture', req.file);
}
form.append('content', JSON.stringify(req.body));
});
app.listen(3000, function() { console.log('listening'); });
因此,当req.file为true时,我收到以下错误:
TypeError: source.on is not a function
at Function.DelayedStream.create (/home/daniel/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
at FormData.CombinedStream.append (/home/daniel/node_modules/combined-stream/lib/combined_stream.js:43:37)
at FormData.append (/home/daniel/node_modules/form-data/lib/form_data.js:68:3)
at /home/daniel/WebstormProjects/CloudA3 Client/CloudA3/skrpt.js:95:18
at Layer.handle [as handle_request] (/home/daniel/node_modules/express/lib/router/layer.js:95:5)
at next (/home/daniel/node_modules/express/lib/router/route.js:131:13)
at Immediate.<anonymous> (/home/daniel/node_modules/multer/lib/make-middleware.js:53:37)
at Immediate.immediate._onImmediate (timers.js:440:18)
at processImmediate [as _immediateCallback] (timers.js:383:17)
got response
{ [Error: socket hang up] code: 'ECONNRESET' }
我猜我需要将req.file转换为其他类型以便传输它,但我无法在任何地方找到任何关于此的信息,也没有任何示例,也无法找出req.file的类型甚至是!
我该如何解决这个问题?
答案 0 :(得分:0)
由于您正在使用multer
和DiskStorage
,req.file
object具有文件内容本地存储在req.file.path
属性中的完整路径。您可以使用此选项通过stream.Readable
创建fs.createReadStream()
并将其直接传递给表单。很容易就可以做到这样的事情。
form.append('uploadPicture', fs.createReadStream(req.file.path))
答案 1 :(得分:0)
我正在通过后端将文件上传到另一台服务器。我目前将 multer
与 MemoryStorage
和 req.file.buffer
一起用于表单数据,我还必须在其中包含文件名,这也会导致正确设置内容类型。
form.append('uploadPicture', req.file.buffer, { filename: req.file.originalname });
也可以从请求中复制内容类型:
form.append('uploadPicture', req.file.buffer, { contentType: req.file.mimetype, filename: req.file.originalname });
我预计该服务的使用率较低,所以对我来说 MemoryStorage
应该没问题,但 DiskStorage
可能更适合您的用例。