GET image from authenticated route

倖福魔咒の 提交于 2021-01-04 04:31:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!