简体   繁体   中英

Uploading File via API Using NodeJS 'fetch'

I am using an existing API call to send a file to our cloud provider via 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. Presently, I keep getting 500 internal server error and am not sure why? 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. 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(),
    },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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