I did a 'get' with fetch but I want to do it with axios, could someone help me convert this code to axios?
detail: detail: I made the request to get an image, and I use the blob to be able to show this image to the user, and I would like to do that with axios as well.
Code:
const image = (url) =>
fetch(url)
.then((response) => {
return response.blob();
})
.then(
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
})
);
const image = async (url) =>
await axios.get(url)
.then(response => {
// can access blog directly from response...
}
Read more about axios here
Here: I am assuming this is a get request?
const image = async (url) => {
return await axios.get(url)
.then((response) => {
return response.blob();
})
.then(
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
})
);
}
Related
I have this code that transforms an image url to base64, it works perfectly but I haven't found a way to convert the result to a string, I need to convert it to a string since I have to POST via an API, any idea I'm doing wrong? :(
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
most likely it's something super simple that I'm failing :(
"what I need is to pass the result that the console.log gives me to show it on the screen as a string"
then just do that
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
document.getElementById("blob-string").innerText = dataUrl;
})
<p id="blob-string"></p>
I have a local pdf file that I want to receive and convert to base64
import file from 'assets/PDFs/file.pdf';
const getBase64 = async (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const fileURI = new File([file], 'file')
const base64Pdf = await getBase64(fileURI);
Finnaly, instead of a base64 file, I got a text file which contain a path to file assets/PDFs/file.pdf
For node environment:
import fs from 'fs'
try {
const data = fs.readFileSync('assets/PDFs/file.pdf', 'utf8')
const buff = new Buffer.from(data)
const base64pdf = 'data:application/pdf;base64,' + buff.toString('base64')
console.log(base64pdf)
} catch (err) {
console.error(err)
}
For browser environment:
const getBase64 = async(file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const file = document.querySelector("input").onchange = async(e) => {
let b64Data = await getBase64(e.target.files[0]);
console.log(b64Data)
}
<input type="file" accept=".pdf" />
I'm trying to using the amazing compressorjs library in my React native expo project.
Currently, I have this:
import Compressor from 'compressorjs';
export const uploadPicture = async (uri, path) => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
new Compressor(blob, { //<--- Problem
quality: 0.6,
maxWidth: 512,
maxHeight: 512,
success(result) {
console.log(result)
},
error(err) {
console.log(err.message)
}
})
blob.close();
//firebase stuff to upload after...
}
I'm assuming this doesn't work because compressorjs only allows File and Blob types and I'm inserting a Promise instead. But I have no clue what to do instead.
If anyone can point me into the right direction, that would be amazing!
Thanks.
Consider using the fetch API response.blob method to get the image blob from the URI as opposed to using Ajax XMLHttpRequest
Like this -
Getting the blob via the URI
let blob = await fetch(uri).then(r => r.blob());
You can also take it a step further by getting the actual file from the blob, like this:
Getting the image file from the blob
let file = await fetch(url)
.then((r) => r.blob())
.then((blobFile) => new File([blobFile], "fileName", { type: "image/png" }));
Your finished code should look something like:
import Compressor from "compressorjs";
export const uploadPicture = async (uri, path) => {
let blob = await fetch(uri).then(r => r.blob());
new Compressor(blob, {
...
});
};
OR this
import Compressor from "compressorjs";
export const uploadPicture = async (uri, path) => {
let file = await fetch(url)
.then((r) => r.blob())
.then((blobFile) =>
new File(
[blobFile],
"fileName",
{ type: "image/png" })
);
new Compressor(file, {
...
});
};
Disclaimer
Please note that there's no guarantee that this suggestion will definitely solve your problem but it's DEFINITELY worth a shot.
Cheers.
I am new to React Native and still learning by doing. I have uploaded images in firebase which I want to show on the second screen. Although, I keep getting errors like
can't find variable: profileImageUrl
I am trying to retrieve the image on the next page.
Here is the code for uploading to firebase:
const uploadImage = async () => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.oneerror = function () {
reject(new TypeError('Network request failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', image, true);
xhr.send(null);
});
const ref = firebase.storage().ref().child('/ankit/');
const snapshot = ref.put(blob);
snapshot.on(
firebase.storage.TaskEvent.STATE_CHANGED,
() => {
setUploading(true);
},
(error) => {
setUploading(false);
console.log(error);
blob.close();
},
() => {
snapshot.snapshot.ref.getDownloadURL().then((url) => {
setUploading(false);
console.log('downlaod url', url);
return url;
});
}
);
};
And here is the code for retrieving:
const [Image, setImage] = useState(false);
let imageRef = firebase.storage().ref('/ankit/');
imageRef
.getDownloadURL()
.then((url) => {
setImage({ profileimageUrl: 'url' });
})
.catch((e) => console.log('getting downloadURL of image error => ', e));
return (
<View>
<Image source={this.state.profileImageUrl}></Image>
</View>
)
You should refactor the code that shows the image. You are using the new hooks state to store the state but try to use it in the html with the syntax of the old react state syntax. This is how it should be:
const [image, setImage] = useState(false);
useEffect(() => {
let imageRef = firebase.storage().ref('/ankit/');
imageRef
.getDownloadURL()
.then((url) => {
setImage(url);
})
.catch((e) => console.log('getting downloadURL of image error => ', e));
},[])
return (
<View>
<Image src={image}></Image>
</View>
);
I want to convert images from a URL to base 64, and store that in a state for later use.
How do I return the data from fetch()?
I can get it to work using CORS safe images and an HTML canvas, but this will not work for public domains.
openImage = (index) => {
const url = formatURLs[index];
const base64 = this.getBase64Image(url);
this.setState(prevState => ({
currentImage: index,
currentImagebase64: base64
}));
}
getBase64Image(url) {
fetch(url).then(r => r.blob()).then(blob => {
var reader = new FileReader();
reader.onload = function() {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
return b64;
};
reader.readAsDataURL(blob);
});
}
When I console.log(reader.result), it will output base64 as expected.
However when I return b64, it returns to openImage as 'undefined'.
getBase64Image is async so when calling it in a sync way it will return undefined.
You can try something like that
openImage = async (index) => {
const url = formatURLs[index];
const base64 = await this.getBase64Image(url);
this.setState(prevState => ({
currentImage: index,
currentImagebase64: base64
}));
}
async getBase64Image(url) => {
const response = await fetch(url);
const blob = await response.blob();
const reader = new FileReader();
await new Promise((resolve, reject) => {
reader.onload = resolve;
reader.onerror = reject;
reader.readAsDataURL(blob);
});
return reader.result.replace(/^data:.+;base64,/, '')
}
You have to set state inside .then()
getBase64Image(url) {
fetch(url).then(r => r.blob()).then(blob => {
var reader = new FileReader();
reader.onload = function() {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
this.setState({
currentImagebase64: b64
});
};
reader.readAsDataURL(blob);
});
}