Home  >  Article  >  Backend Development  >  NodeJs get file to Golang API

NodeJs get file to Golang API

WBOY
WBOYforward
2024-02-08 23:00:101217browse

NodeJs 将文件获取到 Golang API

php editor Baicao recently discovered an interesting technical application: using Node.js to get files to the Golang API. As a lightweight JavaScript running environment, Node.js is famous for its efficient IO operations and non-blocking features. As a high-performance programming language, Golang has excellent performance in handling concurrent tasks and network communication. Combining the two, you can obtain files in Node.js and pass the files to the Golang API for further processing, providing developers with a more flexible and efficient solution. In this article, we will introduce how to use Node.js to get files to the Golang API, and explore its application scenarios in actual projects.

Question content

I try to post via node-fetch to a golang API file with a certain structure, I can make it from postman but not from NodeJS

Hello. I'm at a dead end and I've tried everything...

I need to make a request to golang api, I can create it in Postman: it looks like this: Postman Request

I need to repeat it in NodeJs but I always get a bad request from the API

This is my code on Node

let formData = new FormData()
formData.append('postUUID', postUuid)
json.data.uploadIds.map((upl, index) => {
    let file = data.files.find(el => el == upl.filename)
    formData.append(upl.uuid, fs.readFileSync(file));
})
let headers = new Headers()
headers.append('Authorization', 'Bearer '+token)
headers.append("Accept", "application/json");
fetch(API+'/posts/uploadMediaFiles', {
    method: 'POST',
    headers,
    body: formData
})

The difference from the code generated by Postman is only formdata.append("f2b07a43-f79f-4033-ab2d-bb3176934679", fileInput.files[0], "/file_0.jpg"); and Instead I did formData.append (upl.uuid, fs.readFileSync(file));

Solution

fs.readFileSync( ) Returns a string or Buffer containing only the contents of the file itself. This means that you are only passing the raw contents of the file to FormData.append(), which in turn means that your call to fetch treats the resulting key/value pairs as a file - This only happens when passing a value using the Blob or File types (MDN).

Instead, read the contents of the file as an Array and convert it to a new Blob object, then pass the blob object and the name of the desired file to FormData Field (quick tip on the answer this question):

formData.append(upl.uuid, new Blob([fs.readFileSync(file)]), upl.filename);

The above is the detailed content of NodeJs get file to Golang API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete