'Downloading and Reposting an Image in Node.js
Use case: Download a short-term expiring profile image from URL, and re-post it to my own server for long-term hosting.
First, I download the image data to a string:
const request = require('request-promise');
const img_data = await request(soon_to_expire_url);
I've got a string with binary data now. Now what? Convert it to base64? to a blob? to a stream of some sort?
Next, I need to post the downloaded image to an API for long-term hosting, using axios. The problem is I can only get it work with fs.createReadStream, which requires a file path, not a data string.
const axios = require('axios');
const FormData = require('form-data');
var data = new FormData();
data.append('user_id', user_id);
data.append('profile_file', fs.createReadStream('non-existing-file.jpg'));
var config = {
method: 'POST',
url: 'serverEndpoint',
headers: {
'Content-Type': 'application/json',
...data.getHeaders()
},
data : data
};
return axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
So how can bridge the gap? How can I create something out of the downloaded image that then takes the form of whatever createReadStream produces?
I've tried reducing it to a base64 string starting with data:image/jpeg;base64,..., but that doesn't take.
Last resort would be saving the image to a temp file, then posting that file path, but I would rather avoid that.
Solution 1:[1]
Either way you have to store the file somewhere anyway.
You can try something like this
let file = null;
async function decodeBase64(base64String){
fetch(base64String)
.then(res => res.blob())
.then(blob => {
file = new File([blob], "temp",{ type: "image/png" })
})
}
await decodeBase64(base64String)
var data = new FormData();
data.append('user_id', user_id);
data.append('profile_file', file));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
