I am trying to send an image file to a backend server using a PUT request.
HTML:
<input type="file" name="myFile" id="profilePicInput">
Javacript:
const profileInput = document.getElementById('profilePicInput');
profileInput.addEventListener("change", handleFiles, false);
function handleFiles(){
const formData = profileInput.files[0];
$.ajax({
url: '../uploadImage', //my servlet url
type: 'PUT',
processData: false,
contentType: false,
data: {
data: formData
},
success: function () {
console.log("profile pic updated!");
}
});
}
The problem I'm facing is, in my backend code, I'm receiving data that has a content-type of 'text/plain;charset=UTF-8', but what i need is 'multipart/form-data'.
I've tried two things that didn't work:
Using HTML forms
<form id="profilePicForm" action="javascript:handleFiles()" method="post" enctype="multipart/form-data"> <input type="file" name="myFile" id="profilePicInput"> </form>Javascript:
const profileInput = document.getElementById('profilePicInput'); profileInput.addEventListener("change", submitForm, false); function submitForm(){ document.getElementById("profilePicForm").submit(); }But still the content-type in the request header says 'text/plain;charset=UTF-8' in my PUT request.
Using FormData
function handleFiles(){ const blobFile = profileInput.files[0]; let formData = new FormData(); formData.append("fileToUpload", blobFile); $.ajax({ url: '../uploadImage', //my servlet url type: 'PUT', processData: false, contentType: false, data: { data: formData }, success: function () { console.log("profile pic updated!"); } }); }Same problem. The content-type in the request header still says 'text/plain;charset=UTF-8' in my PUT request.
So my question is: how do you send a file with content-type=multipart/form-data through a PUT request?
UPDATE:
Solution:
HTML:
<input type="file" name="myFile" id="profilePicInput">
Javascript:
const profileInput = document.getElementById('profilePicInput');
profileInput.addEventListener("change", handleFiles, false);
function handleFiles(){
let formData = new FormData();
formData.append("fileToUpload", profileInput.files[0]);
const xhr = new XMLHttpRequest();
xhr.open('PUT', '../uploadImage');
xhr.onload = () => {
console.log("profile updated");
};
xhr.send(formData);
}
type: 'PUT'? That would bemethod: 'put', then if you do a PUT, why don't you send directly the File (using XHR that would bevar xhr = new XMLHttpRequest(); xhr.open('PUT', your_url); xhr.onload = callback; xhr.send(input.files[0]);- Kaiidomethodandaliasare aliases for each other in current jQuery. The value is case insensitive. - Quentintypein the docs... But I didn't meant to imply it was case sensitive anyhow though. - Kaiido