How do I upload a file with the JS fetch API?
I am still trying to wrap my head around it. I can have the user select the file (or even multiple) with the file input:
official document works for me after trying some answers failed: developer.mozilla.org/en-US/docs/Web/API/Fetch_API/… , something can confirm: 1. need wrap file in FromData; 2. doesn’t need to declare Content-Type: multipart/form-data in request header
11 Answers 11
var input = document.querySelector('input[type="file"]') var data = new FormData() data.append('file', input.files[0]) data.append('user', 'hubot') fetch('/avatars', < method: 'POST', body: data >)
You don’t need to wrap the file contents in a FormData object if all you’re uploading is the file (which is what the original question wants). fetch will accept input.files[0] above as its body parameter.
If you have a PHP backend handling the file upload you will want to wrap the file in a FormData so that the $_FILES array is properly populated.
I also noticed that Google Chrome would not show the file in the request payload without the FormData part for some reason. Seems like a bug in Google Chrome’s Network panel.
how would you read this file from let’s say Express backend. As the file is not sent as form data. It is instead sent as just the file object. Does express-fileupload or multer parse such payloads?
This is a basic example with comments. The upload function is what you are looking for:
// Select your input type file and store it in a variable const input = document.getElementById('fileinput'); // This will upload the file after having read it const upload = (file) => < fetch('http://www.example.net', < // Your POST endpoint method: 'POST', headers: < // Content-Type may need to be completely **omitted** // or you may need something "Content-Type": "You will perhaps need to define a content-type here" >, body: file // This is your file object >).then( response => response.json() // if the response is a JSON object ).then( success => console.log(success) // Handle the success response object ).catch( error => console.log(error) // Handle the error response object ); >; // Event handler executed when a file is selected const onSelectFile = () => upload(input.files[0]); // Add a listener on your input // It will be triggered when a file will be selected input.addEventListener('change', onSelectFile, false);
How to Upload Files with JavaScript
Austin Gil
I recently published a tutorial showing how to upload files with HTML. That’s great, but it’s a bit limited to using the native browser form behavior, which causes the page to refresh.
In this tutorial, I want to show you how to do the same thing with JavaScript to avoid the page refresh. That way, you can have the same functionality, but with better user experience.
How to Set Up an Event Handler
Let’s say you have an HTML form that looks like this:
With HTML, to access a file on the user’s device, we have to use an with the “file” type . And in order to create the HTTP request to upload the file, we have to use a element.
When dealing with JavaScript, the first part is still true. We still need the file input to access the files on the device. But browsers have a Fetch API that we can use to make HTTP requests without forms.
I still like to include a form because:
- Progressive enhancement: If JavaScript fails for whatever reason, the HTML form will still work.
- I’m lazy: The form will actually make my work easier later on, as we’ll see.
With that in mind, for JavaScript to submit this form, I’ll set up a “submit” event handler.
const form = document.querySelector('form'); form.addEventListener('submit', handleSubmit); /** @param event */ function handleSubmit(event) < // The rest of the logic will go here. >
Throughout the rest of this article, we’ll only be looking at the logic within the event handler function, handleSubmit .
How to Prepare the HTTP Request
The first thing I need to do in this submit handler is call the event’s preventDefault method to stop the browser from reloading the page to submit the form. I like to put this at the end of the event handler so that if there is an exception thrown within the body of this function, preventDefault will not be called, and the browser will fall back to the default behavior.
/** @param event */ function handleSubmit(event) < // Any JS that could fail goes here event.preventDefault(); >
Next, we’ll want to construct the HTTP request using the Fetch API. The Fetch API expects the first argument to be a URL, and a second, optional argument as an Object.
We can get the URL from the form’s action property. It’s available on any form DOM node which we can access using the event’s currentTarget property. If the action is not defined in the HTML, it will default to the browser’s current URL.
/** @param event */ function handleSubmit(event)
Relying on the HTML to define the URL makes it more declarative, keeps our event handler reusable, and our JavaScript bundles smaller. It also maintains functionality if the JavaScript fails.
By default, Fetch sends HTTP requests using the GET method, but to upload a file, we need to use a POST method. We can change the method using fetch ‘s optional second argument. I’ll create a variable for that object and assign the method property, but once again, I’ll grab the value from the form’s method attribute in the HTML.
const url = new URL(form.action); /** @type [1]> */ const fetchOptions = < method: form.method, >; fetch(url, fetchOptions);
Now the only missing piece is actually including the payload in the body of the request.
How to Add the Request Body
If you’ve ever created a Fetch request in the past, you may have included the body as a JSON string or a URLSearchParams object. Unfortunately, neither of those will work to send a file, as they don’t have access to the binary file contents.
Fortunately, there is the FormData browser API. We can use it to construct the request body from the form DOM node. And conveniently, when we do so, it even sets the request’s Content-Type header to multipart/form-data – also a necessary step to transmit the binary data.
const url = new URL(form.action); const formData = new FormData(form); /** @type [1]> */ const fetchOptions = < method: form.method, body: formData, >; fetch(url, fetchOptions);
That’s really the bare minimum needed to upload files with JavaScript. Let’s do a little recap:
- Access to the file system using a file type input.
- Construct an HTTP request using the Fetch (or XMLHttpRequest ) API.
- Set the request method to POST .
- Include the file in the request body.
- Set the HTTP Content-Type header to multipart/form-data .
Today we looked at a convenient way of doing that, using an HTML form element with a submit event handler, and using a FormData object in the body of the request. The current handleSumit function should look like this:
/** @param event */ function handleSubmit(event) < const url = new URL(form.action); const formData = new FormData(form); /** @type [1]> */ const fetchOptions = < method: form.method, body: formData, >; fetch(url, fetchOptions); event.preventDefault(); >
Unfortunately, the current submit handler is not very reusable. Every request will include a body set to a FormData object and a “ Content-Type ” header set to multipart/form-data . This is too brittle. Bodies are not allowed in GET requests, and we may want to support different content types in other POST requests.
How to Make it Reusable
We can make our code more robust to handle GET and POST requests, and send the appropriate Content-Type header. We’ll do so by creating a URLSearchParams object in addition to the FormData , and running some logic based on whether the request method should be POST or GET . I’ll try to lay out the logic below:
Is the request using a POST method?
— Yes: is the form’s enctype attribute multipart/form-data ?
— — Yes: set the body of the request to the FormData object. The browser will automatically set the “ Content-Type ” header to multipart/form-data .
— — No: set the body of the request to the URLSearchParams object. The browser will automatically set the “ Content-Type ” header to application/x-www-form-urlencoded .
— No: We can assume it’s a GET request. Modify the URL to include the data as query string parameters.
The refactored solution looks like:
/** @param event */ function handleSubmit(event) < /** @type */ const form = event.currentTarget; const url = new URL(form.action); const formData = new FormData(form); const searchParams = new URLSearchParams(formData); /** @type [1]> */ const fetchOptions = < method: form.method, >; if (form.method.toLowerCase() === 'post') < if (form.enctype === 'multipart/form-data') < fetchOptions.body = formData; >else < fetchOptions.body = searchParams; >> else < url.search = searchParams; >fetch(url, fetchOptions); event.preventDefault(); >
I really like this solution for a number of reasons:
- It can be used for any form.
- It relies on the underlying HTML as the declarative source of configuration.
- The HTTP request behaves the same as with an HTML form. This follows the principle of progressive enhancement, so file upload works the same when JavaScript is working properly or when it fails.
Thank you so much for reading. I hope you found this useful. If you liked this article, and want to support me, the best ways to do so are to share it, sign up for my newsletter, and follow me on Twitter.
How to send a file in request node-fetch or Node?
How do I attach a file in Node or Node Fetch POST request? I am trying to invoke an API which will import a CSV or XLS file. Is this possible using Node or Node Fetch?
just to be clear: you want to create an endpoint which will accept file as input and store / process it on your nodejs server using node-fetch ?
Hmm here is my understanding of the question: it does not involve a nodejs server. They want to POST a file to a service (which service is not important) using node-fetch from within a nodejs program (so that program would be an http client from that perspective. It could also be a server for other purposes but that is irrelevant).
2 Answers 2
Use native stream for body, on both request and response.
And sources indicate it supports several types, like Stream , Buffer , Blob . and also will try to coerce as String for other types.
Below snippet shows 3 examples, all work, with v1.7.1 or 2.0.0-alpha5 (see also other example further down with FormData ):
let fetch = require('node-fetch'); let fs = require('fs'); const stats = fs.statSync("foo.txt"); const fileSizeInBytes = stats.size; // You can pass any of the 3 objects below as body let readStream = fs.createReadStream('foo.txt'); //var stringContent = fs.readFileSync('foo.txt', 'utf8'); //var bufferContent = fs.readFileSync('foo.txt'); fetch('http://httpbin.org/post', < method: 'POST', headers: < "Content-length": fileSizeInBytes >, body: readStream // Here, stringContent or bufferContent would also work >) .then(function(res) < return res.json(); >).then(function(json) < console.log(json); >);
hello world! how do you do?
Note: http://httpbin.org/post replies with JSON that contains details on request that was sent.
< "args": <>, "data": "hello world!\nhow do you do?\n", "files": <>, "form": <>, "headers": < "Accept": "*/*", "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Length": "28", "Host": "httpbin.org", "User-Agent": "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)" >, "json": null, "origin": "86.247.18.156", "url": "http://httpbin.org/post" >
If you need to send a file as part of a form with more parameters, you can try:
- npm install form-data
- pass a FormData object as body ( FormData is a kind of Stream , via CombinedStreamlibrary)
- do not pass header in the options (unlike examples above)
const formData = new FormData(); formData.append('file', fs.createReadStream('foo.txt')); formData.append('blah', 42); fetch('http://httpbin.org/post', < method: 'POST', body: formData >)
Result (just showing what is sent):
----------------------------802616704485543852140629 Content-Disposition: form-data; name="file"; filename="foo.txt" Content-Type: text/plain hello world! how do you do? ----------------------------802616704485543852140629 Content-Disposition: form-data; name="blah" 42 ----------------------------802616704485543852140629--