问题
I have a working image-upload front/back-end code working. Now I would like to be able to GET the image from server after it is uploaded.
The problem is that the images must be behind an authenticated route, where user has to pass jwt token in header or body.
When i try to fetch the image like this:
fetch(imageURL, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
I just get a Form object as the response:
<img alt="Your pic" src="[object FormData]">
Would there be some way to get the image into HTML 'img' tag other than just pasting the url in 'src' attribute, since it leads to 401 (Unauthorized)
回答1:
You can try the following snippet:
const myImage = document.querySelector('img');
// I make a wrapper snippet which will resolve to a objectURL
function fetchImage(url, headers) {
return new Promise((resolve, reject) => {
fetch(url, headers)
.then(response => response.blob()) // sending the blob response to the next then
.then(blob => {
const objectUrl = URL.createObjectURL(blob);
resolve(objectUrl);
}) // resolved the promise with the objectUrl
.catch(err => reject(err)); // if there are any errors reject them
});
}
fetchImage(imageUrl, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
})
.then(objectUrl => myImage.src = objectUrl)
.catch(err => console.log(err));
An other example for you to try you can find at: https://davidwalsh.name/convert-image-data-uri-javascript
来源:https://stackoverflow.com/questions/45454974/get-image-from-authenticated-route