我在一个电子商务网站上工作,我一直坚持添加带有照片的产品,我正尝试使用管理员帐户将其作为前端来完成。然而,我对如何渲染和发布我试图发布到我的服务器的文件有点困惑。
我也一直在阅读并制作了这个功能,除了我对如何/在哪里使用它有点不知所措。当我让它工作时,它会将“e30=”放入我的控制台
const generateImageFromBuffer = () => {
const test = new Buffer.from(photos, "base64");
console.log(test.toString("base64"));
return test.toString("base64");
};
这是照片在提交之前在我的控制台中的内容
File {name: 'IMG-0169.jpg', lastModified: 1675124328678, lastModifiedDate: Mon Jan 30 2023 17:18:48 GMT-0700 (Mountain Standard Time), webkitRelativePath: '', size: 2915164, …}
然而,这是作为 products.photos 发送到产品表的内容
photos: {type: 'Buffer', data: Array(2)}
感谢任何有关如何处理这些数据的帮助,这里是与照片有关的大部分工作
产品.js
const [photos, setPhotos] = useState(null);
const onChangePicture = (e) => {
console.log("picture: ", photos);
console.log(e.target.files[0]);
setPhotos(e.target.files[0]);
console.log("picture: ", photos);
};
<input
type="file"
placeholder="Category"
accept="image/*"
onChange={onChangePicture}
/>;
//Where I try and render photos
{
product.photos === null ? (
<p>placeholder</p>
) : (
<img alt="Product Img" src={product.photos}></img>
);
}
api/products.js
productsRouter.post("/:categoryId/products", async (req, res, next) => {
const { categoryId } = req.params;
const { name, description, price, photos, quanity } = req.body;
try {
const productToCategory = await createProduct({
categoryId,
name,
description,
price,
photos,
quanity,
});
console.log(productToCategory);
res.send(productToCategory);
} catch ({ name, message }) {
next({ name, message });
}
});
api/helpers.js
export async function createProducts({
name,
description,
price,
photos,
quanity,
categoryId,
}) {
try {
const response = await fetch(
`http://localhost:8000/api/category/${categoryId}/products`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
// "Content-type": "image"
},
body: JSON.stringify({
name,
description,
price,
photos,
quanity,
categoryId,
}),
}
);
const data = await response.json();
console.log(data);
return data;
} catch (error) {
throw Error(error);
}
}
产品表
CREATE TABLE products (
id SERIAL PRIMARY KEY,
"categoryId" INTEGER REFERENCES product_category ( id ),
"creatorId" INT REFERENCES users ( id ),
"isAvailible" BOOLEAN default true,
name VARCHAR(255) UNIQUE NOT NULL,
description VARCHAR(255) NOT NULL,
price INTEGER NOT NULL,
photos BYTEA,
quantity INT
);