使用JS和NodeJS上传文件发布请求

时间:2018-06-24 07:13:41

标签: javascript node.js post request xmlhttprequest

我有以下请求,我想将其写为在nodejs中的发布请求:

POST / rest-api / hashDb / createAndUpload HTTP / 1.1

主机:192.168.101.54

连接:保持活动状态

内容长度:428

来源:https://192.168.101.54

用户代理:Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 67.0.3396.87 Safari / 537.36

Content-Type:multipart / form-data; boundary = ---- WebKitFormBoundaryQGLkZW0bVDsvWPEY

接受: /

引荐来源:https://192.168.101.54/ufed/index.html

接受编码:gzip,deflate,br

接受语言:en-US,en; q = 0.9,es; q = 0.8,he; q = 0.7

Cookie:JSESSIONID = s3a5sjc6wp1y1k9hv5advlf3a

这是我编写的代码,但无法完成工作(文件未上传):

var FormData = require('form-data');
var fs = require('fs');
var request = require("request")
// var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

let filePath = "C:\\Temp\\directory.txt" 
let myFile = fs.readFileSync(filePath,'utf8');
var formData = new FormData();
formData.append("myFile", myFile, "directory.txt");
var bounding = {"id":null,"type":"HashDbDto","name":"jorge1","fileType":"TXT","version":"1.2","redaction":false,"categories":[],"format":"MD5"};
formData.append("myFile", JSON.stringify(bounding));

request({
    headers: {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryeiNygPyQcm8jomRB'},
    url: "https://192.168.101.54/rest-api/hashDb/createAndUpload",
    method: "POST",
    form: formData
});

我想念什么?

1 个答案:

答案 0 :(得分:0)

使用formData键而不是form

request({
   headers: {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryeiNygPyQcm8jomRB'},
   url: "https://192.168.101.54/rest-api/hashDb/createAndUpload",
   method: "POST",
   form: formData
})

请参见https://www.npmjs.com/package/request。 对于多部分/表单数据,我们使用@felixge提供的表单数据库。在大多数情况下,您可以通过formData选项传递上传表单数据。