Cloudinary Bad Request 400 Hosting Imgs on Cloudinary Image Hosting
Hello, dear Cloudinary team, I'm stuck with troubishooting hosting images on Cloudinary image hosting. I'm experiencing an error bad request 400, and I'm trying to solve it. POST https://api.cloudinary.com/v1_1/dexs7ahqs/image/upload 400 (Bad Request). This is the message in the console. My upload preset is unsigned. Here's the code:
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("attachment").files;
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
return srcData;
};
fileReader.readAsDataURL(fileToLoad);
}
function uploadFile(file) {
const url = `https://api.cloudinary.com/v1_1/${vars.CLOUDINARYACCOUNT}/image/upload`;
const xhr = new XMLHttpRequest();
const fd = new FormData();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = (e) => {
if (xhr.readyState == 4 && xhr.status == 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
console.log(vars.UPLOADPRESET)
fd.append(
"upload_preset",
vars.UPLOADPRESET
);
fd.append("tags", "browser_upload");
fd.append("file", file);
xhr.send(fd);
}
export default function WritePost() {
useEffect(() => {
document
.querySelector("#post")
.addEventListener("click", async function uploadImage() {
// file from <input type="file">
let file = document.querySelector("#attachment").value;
const fileConverted = encodeImageFileAsURL();
console.log(uploadFile(fileConverted))
});
}, []);
I'm building a MERN app, please help me, my team is waiting for me and we hope you'll be able to help us! Sincirely, Larisa!
-
Hi Larisa,
I went ahead and checked the upload logs on our side for your cloud and I see the reason for the 400 Bad Request errors. From the logs, we can see that the value coming through for the 'file' parameter in the upload requests is actually 'undefined' which then means the upload is rejected.
May I please ask you to check/log the value of the `file` object before it's added as part of the FormData? You could also try to hardcode a Base64 String for an image as the value of the `file` parameter and send an upload request with it to test/ensure the rest of the upload works. Once you've established that you can understand where the undefined value for the `file` parameter was originating from.
Please let me know how it goes.
1
Post is closed for comments.
Comments
1 comment