Reputation: 927
I'm using rn-fetch-blob library to download and save a file into the device, and I've been successful to do it with GET request like: .fetch('GET', "http://api.pdflayer.com/api/convert?access_key=MY_ACCESS_KEY&document_url=URL_PATH")
, but the API that I use just accepts post request, so I tried this but didn't work:
const { config, fs } = RNFetchBlob;
let DownloadDir = fs.dirs.DownloadDir;
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
path: DownloadDir + "/file.pdf"
}
};
const data = JSON.stringify({
access_key: "MY_ACCESS_KEY",
document_url: "https://pdflayer.com/downloads/invoice.html"
});
config(options)
.fetch('POST', 'http://api.pdflayer.com/api/convert', {body: data})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err)
})
If I'm not sending my request correctly, so how should I do it? thanks in advance.
Upvotes: 0
Views: 4146
Reputation: 297
According to the rn-fetch-blob's document :
headers:object (Optional) Headers of HTTP request, the value of headers should be stringified, if you're uploading binary files, content-type should be application/octet-stream or multipart/form-data(see examples above).
body:string | Array (Optional) Body of the HTTP request, body can either be a BASE64 string, or an array contains object elements, each element have 2 required property name, data, and optional property filename, once filename is set, content in data property will be considered as a path to a file or a BASE64 string which will be converted into byte array later.
I think you should define content-type for your request and change your code like these examples :
// Post binary data using base64 encoding
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', {
'Content-Type' : 'application/octet-stream'
}, RNFetchBlob.base64.encode(mydata))
// Post binary data from existing file
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', {
'Content-Type' : 'application/octet-stream'
}, RNFetchBlob.wrap(path_to_the_file))
// Post form data
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', {
'Content-Type' : 'multipart/form-data'
}, [
{ name : 'user_name', data : 'Bill' },
// binary field data from a file path, use `wrap` method to wrap the path
{ name : 'avatar', filename : 'avatar.jpg', data : RNFetchBlob.wrap(path_to_the_file) },
// binary field data encoded in BASE64
{ name : 'pet-avatar', filename : 'pet-avatar.jpg', data : RNFetchBlob.base64.encode(image_data) },
])
I hope that helps :)
Upvotes: 2