React is used in this project. Images should be uploaded to the backend into a media folder. I would like to use the following request generated in postman in my JavaScript code:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer /*Token has been removed to keep it secret.*/ ");
var formdata = new FormData();
formdata.append("title", "A lot of Piano");
formdata.append("description", "Many Pianos for Classic Piano");
formdata.append("condition", "2");
formdata.append("has_for_this_item", "Anything");
formdata.append("tags", "7");
formdata.append("images", fileInput.files[0], "/C:/Users/Christian/OneDrive/Bilder/Diashow/ISchgl, Schwarzwasser See.jpg");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://127.0.0.1:8000/backend/api/wants/me/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Below, you’ll see the response from postman:
{
"id": 6,
"author": {
"id": 1,
"user": {
"id": 2,
"username": "ChrisLiberty"
},
"location": "Chur, Switzerland"
},
"tags": [
7
],
"description": "Many Pianos for Classic Piano",
"title": "A lot of Piano",
"condition": 2,
"has_for_this_item": "Anything",
"created_time": "2023-02-08T13:33:54.642828Z",
"updated_time": "2023-02-08T13:33:54.642828Z",
"images": [
{
"id": 6,
"images": "/media/1/ISchgl_Schwarzwasser_See_SqgdKUm.jpg",
"want": 6
}
]
}
I have modified the code a little bit for my needs and I’ve added the following code to into my JavaScript file:
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${user.acces}`);
var formdata = new FormData();
formdata.append("title", "A lot of Piano");
formdata.append("description", "Many Pianos for Classic Piano");
formdata.append("condition", "2");
formdata.append("has_for_this_item", "Anything");
formdata.append("tags", "7");
formdata.append("images", URL.createObjectURL(document.getElementById("images").files[0]), "/C:/Users/Christian/OneDrive/Bilder/Diashow/ISchgl, Schwarzwasser See.jpg");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch(`${baseUrl}/backend/api/haves/me/`, requestOptions)
.then(response => response.json())
.then(result => {
setAction("created")
})
.catch(error => {
console.log('error', error)
setAction("error")
});
I’ve received the following error message:
Uncaught TypeError: Failed to execute ‘append’ on ‘FormData’: parameter 2 is not of type ‘Blob’.
The error makes a reference to the following line of code:
formdata.append("images", URL.createObjectURL(document.getElementById("images").files[0]), "/C:/Users/Christian/OneDrive/Bilder/Diashow/ISchgl, Schwarzwasser See.jpg");
I’m looking for a solution to fix it. My aim is that the Create Opertion started in the Java Script file is working as it works in Postman.