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:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit
event using <fill in your event handler here>
. But once I do, how do I send the file using fetch
?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
This is a basic example with comments. The
upload
function is what you are looking for:I've done it like this:
An important note for sending Files with Fetch API
One needs to omit
content-type
header for the Fetch request. Then the browser will automatically add theContent type
header including the Form Boundary which looks likeForm boundary is the delimiter for the form data
If you want multiples file, you can use this
To submit a single file, you can simply use the
File
object from theinput
's.files
array directly as the value ofbody:
in yourfetch()
initializer:This works because
File
inherits fromBlob
, andBlob
is one of the permissibleBodyInit
types defined in the Fetch Standard.Jumping off from Alex Montoya's approach for multiple file input elements
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
Fetch seems to recognize that format and send the file where the uri is pointing.