How to upload a file using the HTTP PUT method using JavaScript's fetch() API
For my own future reference
Personal note:
Apparently the number of posts and articles showing how to make a PUT request to upload a file using the fetch API is too low for Google to show them when I occasionally need it, so here’s the code snippet. I hope to find it next time I need it :)
async function uploadFile() {
const fileInput = document.getElementById('fileInput');
if (fileInput.files.length == 0) {
alert("No file selected");
return;
}
const f = input.files[0];
try {
const response = await fetch("{{ base_url }}/api/mediafileupload", {
method: "PUT",
body: f,
headers: {
'Content-Type': file.type
}
});
const result = await response.json();
console.log("Success:", result);
} catch (error) {
console.error("Error:", error);
}
}
The key is that the INPUT DOM element with FILE type actually contains File
objects, which can be passed as the body
argument to fetch()
.