How do you post FormData with a duplex (or transform) stream?
#1674
-
|
I was trying to fetch a file from a remote URL and upload it to a different url without saving it to the disk first. That wasn't working and i was getting a // working:
const readStream = fs.createReadStream("file.txt");
const form = new FormData();
form.append("file", readStream);
got.post("https://destination.url", {
body: form
});
// not working:
const remoteFileStream = got.stream("https://remote-file.url")
const form = new FormData();
form.append("file", remoteFileStream);
got.post("https://destination.url", {
body: form
});
// not working:
const readStream = fs.createReadStream("file.txt");
const transformStream = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk);
},
});
const form = new FormData();
form.append("file", readStream.pipe(transformStream));
got.post("https://destination.url", {
body: form
});
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
|
I have the same question. |
Beta Was this translation helpful? Give feedback.
-
|
hi @zzlPetrichor , would you be able to share the code snippet how you got it to work? I tried the same way (passing in response) but unable to get it to work. Here's my code: |
Beta Was this translation helpful? Give feedback.
-
|
Posting FormData with streams can be tricky because FormData needs to know the content length upfront. Here's the recommended approach: import got from 'got';
import FormData from 'form-data';
// Fetch the file as a stream
const sourceStream = got.stream('https://example.com/file.pdf');
// Wait for response event to get headers (including content-length)
sourceStream.on('response', (response) => {
const form = new FormData();
form.append('file', sourceStream, {
filename: 'file.pdf',
contentType: response.headers['content-type'],
knownLength: parseInt(response.headers['content-length'], 10)
});
// Upload the form
got.post('https://upload.example.com', {
body: form
});
});The key is providing If the source doesn't provide a content-length header, you'll need to buffer the stream first, which defeats the puprose of streaming. |
Beta Was this translation helpful? Give feedback.
Posting FormData with streams can be tricky because FormData needs to know the content length upfront. Here's the recommended approach: