How to download then again upload blob in Javascript using Fetch Api - javascript

In the following snippet downloading works as expected but uploading is not working, getting a HTTP 500 response. The issue isn't backend as it works in Postman or equivalent.
What could be the issue?
return fetch('url', {
method: 'GET',
}).then((response) => {
//upload
if (response.status === 200) {
let blob = response.blob();
return fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
},
body: blob,
}).then((response) => {
console.log(response.status);
});
}
});

Try using form data,
if (response.status === 200) {
let blob = response.blob();
const formData = new FormData();
formData.set('file', blob);
return fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: blob,
}).then((response) => {
console.log(response.status);
});
}

Related

React native image upload getting network error

'react-native-image-picker' for uploading image in my application, Sometimes it is uploading and sometimes i am getting [TypeError: Network request failed] below is the code:
FormData in my component:
//image is :file:///data/user/0/com.testApp/cache/rn_image_picker_lib_temp_0d38d959-6ece-4750-a215-4b3f68002f4e.jpg
let formData = new FormData();
formData.append('images', { uri:image, name: imageSelected?.fileName, type: 'image/png' });
const response = await updateUserProfile(userDetails,formData)
Service call:
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: data,
});
return await response;
};
In Postman i have checked the api is working fine, What would be the problem in my code.
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: JSON.stringify(data),
});
return await response;
};

Convert base64 image to send as multipart/form-data

There is a system. The frontend is written in react and the backend in java.
On the frontend part, there is an image (base64) and some fields (string) that need to be sent to the server.
'Content-Type': 'multipart/form-data'
I also know that on the backend, the image must have a MultipartFile type
I do not understand what format I need to convert the picture to.
Can you please advise me?
const formData = new FormData();
formData.append( 'image', store.image); // store.image - base64
formData.append( 'id-number-value', "id");
formData.append( 'id-number-type', "id_card");
fetch('/path', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
} )
.then((response) => {
if (response.ok) {
resolve();
} else {
throw new Error(response.message);
}
})
.catch((error) => reject(error));
You can convert the base64 string to a blob first.
const formData = new FormData();
formData.append('id-number-value', "id");
formData.append('id-number-type', "id_card");
fetch(store.image)
.then(res => res.blob()).then(blob => {
formData.append('image', blob);
fetch('/path', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then((response) => {
if (response.ok) {
resolve();
} else {
throw new Error(response.message);
}
})
.catch((error) => reject(error));
});

Generate body for multipart file upload using fetch in Javascript

I am trying to upload a file(uploadType=multipart) to Drive API V3 using fetch but the body is wrong as it is creating a file with the title unnamed.
var tmpFile=document.getElementById('inputFile').files;
tmpFile=tmpFile[0];
await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST', // or 'PUT'
headers: {
'Authorization': 'Bearer '+accessToken,
},
body: {
metadata:{
'name':tmpFile.name,
'Content-Type':'application/json; charset=UTF-8'
},
media:{
'Content-Type': '*/*',
'name':tmpFile
}
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Your metadata is not being properly uploaded if its uploading with a name of unnamed
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const filePath = "./sample.txt";
const accessToken = "###";
token = req.body.token;
var formData = new FormData();
var fileMetadata = {
name: "sample.txt",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
contentType: "application/json",
});
formData.append("data", fs.createReadStream(filePath), {
filename: "sample.txt",
contentType: "text/plain",
});
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
method: "POST",
body: formData,
headers: { Authorization: "Bearer " + accessToken },
})
.then((res) => res.json())
.then(console.log);
Uploading Files of multipart/form-data to Google Drive using Drive API with Node.js

Javascript node-fetch usage

I can get the data by request from this code.
let request = require('request');
let options = {
'method': 'POST',
'url': 'https://example.com/api',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '12345678',
'client_secret': 'abcdefg'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?
const fetch = require("node-fetch");
const url = "https://example.com/api";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var data = JSON.stringify( {
'client_id': '12345678',
'client_secret': 'abcdefg'
});
fetch(url, {method: 'POST', headers: headers, body: data})
.then(response => response.json())
.then((resp) => {
console.log(resp);
})
.catch(error => console.error('Unable to fetch token.', error));
'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?
The documentation tells you how to encode data as form parameters.
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);

Error when POST file multipart/form-data (JavaScript)

I got an error every time when trying to POST data to the API.
Request:
changeUserAvatar(authParam, file) {
let formData = new FormData();
//file is actually new FileReader.readAsDataURL(myId.files[0]);
formData.append('profile_image', file);
fetch(BASE_URL + 'profile-image', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': authParam
},
body: formData
}).then((response) => {
return response.json();
}).then((response) => {
debugger;
}).catch((error) => {
console.error(error);
});
}
Error: profile_image can not be blank (422).
But it's not blank!
Request payload:
What do I do wrong?
Solved at GutHub: https://github.com/github/fetch/issues/505
I just had to leave Header without pointing any Content-Type manually.

Categories