我有一个正在运行的图像上传前端/后端代码。现在我希望能够在上传后从服务器获取图像。
问题是图像必须位于经过身份验证的路由后面,用户必须在标头或正文中传递 jwt 令牌。
当我尝试像这样获取图像时:
fetch(imageURL, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
我只是得到一个 Form 对象作为响应:
<img alt="Your pic" src="[object FormData]">
除了将 url 粘贴到“src”属性中之外,是否还有其他方法可以将图像放入 HTML“img”标签中,因为它会导致401 (Unauthorized)
您可以尝试以下代码片段:
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));
您可以在以下位置找到另一个供您尝试的示例:https://davidwalsh.name/convert-image-data-uri-javascript https://davidwalsh.name/convert-image-data-uri-javascript
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)