Skip to content
Discussion options

You must be logged in to vote

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
	});
});

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@kiyutink
Comment options

@zzlPetrichor
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by sindresorhus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants