【发布时间】:2019-01-25 10:56:42
【问题描述】:
我正在尝试从 blob 呈现 <img>。
import React from 'react';
import { getImageBlob } from '../api/images';
class ImageViewer extends React.Component {
state = {
src: undefined,
loading: true,
}
componentDidMount() {
getImageBlob()
.then((imageBlob) => {
console.log(imageBlob);
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(imageBlob);
console.log(imageUrl);
this.setState({ src: imageUrl, loading: false });
})
.catch((err) => {
console.error(err);
this.setState({ loading: false });
});
}
render() {
if (this.state.loading) {
return 'loading';
}
return <img src={this.state.src} height={100} width={100} />;
}
}
export default ImageViewer;
第一个console.log() 的输出类似于:
Blob(5842218) {size: 5842218, type: "application/json"}
我认为type 可能是它不渲染的原因,但我不确定。
第二个console.log() 的输出类似于:
blob:http://localhost:3000/12bfba06-388d-48e2-8281-5ada40a662de
getImageBlob() 函数是:
export const getImageBlob = () => new Promise((res, rej) => {
client
.get(`${IMAGES}`, {
responseType: 'blob',
})
.then((resp) => {
res(resp.data);
})
.catch((err) => {
rej(Error(err.message));
});
});
服务器发回的内容可能不正确,因此我可以在必要时发布该代码。
使用服务器代码更新
这是发回图像 blob 的代码。
const getImage = (imageKey) => {
const params = {
Bucket: process.env.S3_BUCKET,
Key: imageKey,
};
return new Promise((res, rej) => {
s3.getObject(params, (err, data) => {
if (err) {
rej(Error(err.message));
} else {
console.log(data);
res(data);
}
});
});
};
console.log() 在服务器端的输出:
{ AcceptRanges: 'bytes',
LastModified: 2018-08-18T18:07:39.000Z,
ContentLength: 2101981,
ETag: '"be594978d48fdc5964eb97ffb2c589f1"',
ContentEncoding: 'blob',
ContentType: 'image/jpg',
Metadata: {},
Body:
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 27 10 00 00 27 10 08 06 00 00 00 ba 4e 62 27 00 00 20 00 49 44 41 54 78 5e ec d0 01 0d 00 30 08 ... > }
【问题讨论】:
-
问题在于您的内容类型。从 blob 的大小可以清楚地看出,服务器正在正确地完成它的工作,只是您的客户端出现了问题。我相信这个副本解决了提供图片的问题。
-
感谢您的评论。那么,
responseType: 'blob'不是设置内容类型的正确方法吗? -
@TravisJ 你链接的问题似乎只涉及 Node.js,除非我遗漏了什么?
-
它确实主要针对 Node.js(您在此处也标记了它),但是我链接该副本的主要原因是因为
responseType不是设置内容类型的正确方法,您需要在请求标头中指出contentType,重复覆盖。 -
在
getImageBlob()中将contentType设置为image/jpeg似乎不起作用。是否应该设置为application/json?
标签: javascript html node.js reactjs