无法显示图像反应



我使用邮递员为我创建的 API 保存了一张图像。 图像的保存方式是:

const newProduct = new Product({
name: req.body.name,
referenceId: createReferenceId(),
category: req.body.category,
image: {
data: fs.readFileSync(req.body.image),
contentType: "image/jpg"
},
metadata: req.body.metadata
});
newProduct
.save()
.then(product => res.json(product))
.catch(err => res.json(err));

我的猫鼬模式如下所示:

const ProductSchema = new Schema({
name: { type: String, required: true },
referenceId: { type: String, required: true },
category: { type: String, required: true },
image: { contentType: String, data: Buffer },
metadata: { type: String }
});

我存储的数据如下所示:

[255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 2, 1, 0, 100, 0, 100, 0, 0, 255, 225, 13, 5, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 7, 1, 18, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 1, 26, 0, 5, 0, 0, 0, 1, 0, 0, 0, 98, 1, 27, 0, 5, 0, 0, 0, 1, 0, 0, 0, 106, 1, 40, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1, 49, 0, 2, 0, 0, 0, 20, 0, 0, 0, 11]

我想在 reactJS 中显示这个保存的图像?我很困惑我怎么能这样做。请帮忙。

您可以将图像另存为数据URL。以下是我创建的承诺,以便从拖放区组件中提取图像数据。

const promise = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(filesToUpload[0]);
reader.onload = () => {
if (reader.result) {
resolve(reader.result);
} else {
reject(Error('Failed converting to base64'));
}
};
});

然后,您可以使用 promise 中的then()方法访问数据。

promise.then((result) => {
// This is the result
console.log(result);
}, (err) => {
console.log(err);
});

检索数据URL后,将其发布到API。然后,您可以轻松地使用<img>中的src属性来显示图像。

希望这有帮助。干杯!

将数组缓冲区转换为 base64 并在 html 部分中使用该变量。

let arrayBuffer = "Your data from api";
var base64Val = window.btoa(
new Uint8Array(arrayBuffer).reduce((data, byte) => 
data + String.fromCharCode(byte), ''
)
);
<img src={`data:image/jpeg;base64,${base64Val}`} />

最新更新