在我的项目中,我将Multipart表单数据从角度侧发送到nodejs。我收到的数据格式是
{ name: 'customer.test.14',
email: 'test14@gmail.net',
website: 'www.google.com',
contact_name: 'Vijay',
contact_number: '+123456789022',
profile: 'Testing',
provider_category: 'exchange',
services_offered: 'Testing',
description: 'Test',
image:
[ { size: 1474,
type: 'image/png',
path: 'bc31dac580a7c2086f306fe0b9b5182d/',
basename: 'icon_dd_chart_grey.png' } ] }
我想将数据发送到nodejs中的另一个api。但api不上传图片。
这是我的代码
var request = require('request');
var api_url = global.common.base_url + 'vcard/1.0.0/visit_card/' + req.param('uuid') +'/';
console.log(req.body);
request({
url: api_url,
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data;',
'Authorization': 'Bearer '+req.cookies.apitoken
},
json: req.body,
}, function(error, response, body) {
if(response.statusCode == 200 && !error){
res.end(JSON.stringify(body));
}else{
res.send(response.statusCode, { error: body });
}
});
答案 0 :(得分:2)
您可以使用“ Okhttp3 ”将其存档。请refer this video tutorial form reference and usage和documentation。
例如:将两个主体(json和图像)同时上传到单个端点:
const okhttp = require('okhttp');
var MimeBuilder = okhttp.MimeBuilder;
var Request = okhttp.Request;
var RequestBody = okhttp.RequestBody;
var RequestBuilder = okhttp.RequestBuilder;
var FormEncodingBuilder = okhttp.FormEncodingBuilder;
var MultiPartBuilder = okhttp.MultiPartBuilder;
let json = JSON.stringify({title:'test'});
var image = fs.readFileSync(path.resolve(__dirname, 'test.jpg'));
let mp_body = new MultiPartBuilder().addPart(RequestBody.create(json, 'Content-Type: application/json; charset=UTF-8'))
.addPart(RequestBody.create(image, new MimeBuilder().contentType('image/jpeg').contentTransferEncoding('binary').build()))
.type(MultiPartBuilder.FORMDATA).build();
new RequestBuilder().url('https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart')
.header('Authorization', 'Bearer OAUTH2_TOKEN_HERE')
.POST(mp_body).buildAndExecute().then(console.log).catch(console.error);