从认证的路径获取图像
问题描述:
我有一个工作的图像上传前端/后端代码工作。现在我希望能够在上传后从服务器获取图像。从认证的路径获取图像
问题是图像必须位于经过验证的路由之后,其中用户必须在标头或正文中传递jwt令牌。
当我尝试获取这样的形象:
fetch(imageURL, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
我只是得到一个表单对象作为回应:
<img alt="Your pic" src="[object FormData]">
会不会有某种方式来获得图像转换成HTML“ IMG”标签的其他不仅仅是粘贴在URL‘SRC’属性,因为它导致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
谢谢:)我刚得到它通过编码使用Base64的文件发送到前端工作之前,并在前端图像标签在图像二进制数据之前添加'data:image/png; base64'。 –
这也是一个体面的想法... –