简体   繁体   English

使用 NodeJS 'fetch' 通过 API 上传文件

[英]Uploading File via API Using NodeJS 'fetch'

I am using an existing API call to send a file to our cloud provider via Nodejs.我正在使用现有的 API 调用通过 Nodejs 将文件发送到我们的云提供商。 I have seen several different methods of doing this online, but figured I would stick to using "fetch" as most of my other API calls have been using this as well.我已经在网上看到了几种不同的方法来执行此操作,但我认为我会坚持使用“获取”,因为我的大多数其他 API 调用也一直在使用它。 Presently, I keep getting 500 internal server error and am not sure why?目前,我不断收到 500 内部服务器错误,我不确定为什么? My best conclusion is that I am not sending the file properly or one of my pieces of formdata are not resolving correctly.我最好的结论是我没有正确发送文件,或者我的一个表单数据没有正确解析。 See the below code:请参阅以下代码:

 const fetch = require("node-fetch"); const formData = require("form-data"); const fs = require("fs"); var filePath = "PATH TO MY FILE ON SERVER WITH FILE NAME"; var accessToken = "Bearer <ACCESS TOKEN>; var url = '<API URL TO CLOUD PROVIDER>'; var headers = { 'Content-Type': 'multipart/form-data', 'Accept': 'application/json', 'Authorization': accessToken }; const form = new formData(); const buffer = fs.readFileSync(filePath); const apiName = "MY_FILE_NAME"; form.append("Content-Type", "application/octect-stream"); form.append("file", filePath); console.log(form); fetch(url, { method: 'POST', headers: headers, body: form }).then(response => response.json()).then(data => { console.log(data) }).catch(err => { console.log(err) });

This my first time attempting something like this so I am next to certain I am missing something.这是我第一次尝试这样的事情,所以我几乎可以肯定我错过了一些东西。 Any help with getting me in the right direction is appreciated.感谢任何帮助我朝着正确方向前进的帮助。

So the issue was exactly what I mentioned above.所以这个问题正是我上面提到的。 The code was not uploading the file I specified.代码没有上传我指定的文件。 I finally figured out why and below is the modified code which will grab the file and upload to our cloud service provide:我终于明白了为什么,下面是修改后的代码,它将抓取文件并上传到我们的云服务提供:

 const fetch = require("node-fetch"); const formData = require("form-data"); const fs = require("fs"); var apiName = process.env['API_PATH']; var accessToken = "Bearer" +" "+ process.env['BEARER_TOKEN']; var url = process.env['apiEnv'] +"/" +"archive"; var headers = { 'Accept': 'application/json', 'Authorization': accessToken, }; const form = new formData(); const buffer = fs.readFileSync(apiName); const uploadAPI = function uploadAPI() { form.append("Content-Type", "application/octet-stream"); form.append('file', buffer); fetch(url, {method: 'POST', headers: headers, body: form}) .then(data => { console.log(data) }) .catch(err => { console.log(err) }); }; uploadAPI();

Being new to Javascript/Nodejs I wasn't really sure what the "buffer" variable did.作为 Javascript/Nodejs 的新手,我不太确定“缓冲区”变量做了什么。 After finally figuring it out I realized I was adding too many body form params to the request and the file was not being picked up and sent to the provider.终于弄清楚之后,我意识到我在请求中添加了太多的正文表单参数,并且文件没有被提取并发送给提供者。 All code above is using custom variables, but if for whatever reason someone wants to use it, then simply replace the custom variables with your own....Thanks again for any and all assistance....上面的所有代码都使用自定义变量,但是如果出于某种原因有人想要使用它,那么只需将自定义变量替换为您自己的……再次感谢您的任何帮助……

import fs from 'fs'
import FormData from 'FormData';

const fileStream = fs.createReadStream('./file.zip');
const form = new FormData();

form.append('key', fileStream, 'file.zip');

const response = await axios.post(url, form, {
    headers: {
        ...form.getHeaders(),
    },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM