我正在尝试使用Restify模块将图像文件上传到Rest服务器(Confluence更具体),但是收到Assertion错误。我不确定我是否使用正确的方法将文件上传到REST服务器。有人能指出我正确的方向吗?
这是我的尝试 -
var restify = require('restify');
var header = {'Authorization': 'Basic xxxxx', 'content-type': 'multipart/form-data'};
var client = restify.createJsonClient({
url: 'http://www.testsite.com',
version: '*',
headers: header
});
var image = "c:\\Users\\abc\\Documents\\bbb.jpg";
var fileStream = fs.createReadStream(image);
var stat = fs.statSync(image);
var size = stat["size"];
var param = "?pageId=123&filename=mynewimage&mimeType=image%2Fjpeg&size=" + size;
fileStream.pipe(
client.post("/plugins/drag-and-drop/upload.action"+param, function(err, req, res, obj) {
if (err) {
return err;
}
})
);
更新:
这是一个断言错误我得到assert.js:86
throw new assert.AssertionError({ ^ AssertionError: body at Object.module.exports.(anonymous function) [as ok] (c:\Users\abc\myproj\node_modules\restify\node_modules\assert-pl us\assert.js:242:35) at JsonClient.write (c:\Users\abc\myproj\node_modules\restify\lib\clients\json_client.js:31:12) at ReadStream.ondata (_stream_readable.js:540:20) at ReadStream.emit (events.js:107:17) at readableAddChunk (_stream_readable.js:163:16) at ReadStream.Readable.push (_stream_readable.js:126:10) at onread (fs.js:1683:12) at FSReqWrap.wrapper [as oncomplete] (fs.js:529:17)
答案 0 :(得分:2)
我一直在努力发送包含multipart/form-data
的请求并使用restify 5
在API上处理此请求。在@mscdex回答后,我想出了以下代码来处理这两种情况:
"use strict"
const restify = require('restify'),
plugins = require('restify-plugins'),
fs = require('fs'),
request = require('request'),
FormData = require('form-data');
var server = restify.createServer();
server.use(plugins.multipartBodyParser()); // Enabling multipart
// Adding route
server.post('/upload', (req, res, next) =>{
/**
* Processing request containing multipart/form-data
*/
var uploaded_file = req.files.mySubmittedFile; // File in form
//Reading and sending file
fs.readFile(uploaded_file.path, {encoding: 'utf-8'}, (err, data)=>{
// Returning a JSON containing the file's name and its content
res.send({
filename: uploaded_file.name,
content: data
});
next()
});
});
// Launching server at http://localhost:8080
server.listen(8080, start);
// Client request
function start(){
// Making a request to our API using form-data library
// Post file using multipart/form-data
var formData = {
mySubmittedFile: fs.createReadStream('/tmp/hello.txt')
}
request.post({'url': 'http://localhost:8080/upload', formData: formData}, function(err, res, body){
console.log("Response's body is: "+ body);
});
}
使用:
我尝试不使用库form-data
和request
来仅使用restify / http但我最终得到了一个可怕的长代码。
答案 1 :(得分:0)
要发送multipart/form-data
,您必须使用restify
以外的库,因为它不支持Content-Type
。
您可以使用支持内置multipart/form-data
http请求的request
。