嗨,我多年来一直在尝试上传 tar 文件,但每次都失败。我是这个 JS、UI 和 https req/res 域的新手。 我的环境是:nodeJS,后端的JavaScript。 ReactJS 前端。 我需要将 tar 文件从我的机器上传到远程服务器。
这是我的前端代码,我在其中发出提取请求来上传文件。
export function postXCCDF () {
let _headers = {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu'
};
var formData = new FormData();
formData.append('type', 'file');
formData.append('file', 'C:\\MyDrive\\rules.zip');
let uri = '/rest/policy';
const options = { method: 'POST', headers: _headers, body: formData };
return fetch(`${_host}${urlPrefix}${uri}`, options)
.then(processStatus)
.then(response => response.json());
}
这是我的后端代码,我希望在其中接收 tar 文件。
router.post('/policy', function(req, res) {
console.log('hey I reached here');
console.log('hemant req',req.body.formData); // prints hemant req undefined
// Dont know how to save it to some directory. ??? :(
});
我的整个想法是将 tar 文件上传到位于远程位置的服务器。我尝试了很多其他方法,但似乎没有任何帮助。
最佳答案
body-parser 模块仅处理 JSON 和 urlencoded 表单提交,而不处理多部分(如果您上传文件,就会出现这种情况)。
对于多部分,您需要使用类似 connect-busboy 的内容或multer或connect-multiparty (multiparty/formidable 最初是在express bodyParser 中间件中使用的)。
关于javascript - 在 javaScript 中使用 fetch API 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43276231/