我做了這個函式,它從檔案狀態中獲取檔案值(影像)并將其發送到上傳路由,通過FormData物件
const [file, setFile] = useState(null);
const submitPost = async (e) => {
...
e.preventDefault();
if (file) {
const data = new FormData();
const fileName = `${Date.now()}${file.name}`;
data.append("name", fileName);
data.append("file", file);
try {
await fetch("http://localhost:8000/upload", {
headers: {
"Content-type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
});
// window.location.reload();
} catch (err) {
console.log(err);
}
}
};
檔案狀態中的檔案值來自表單檔案輸入
<form className="postOptions" onSubmit={submitPost}>
<div className="postAreaBot">
<label htmlFor="file" className="downloadImg">
<AddAPhotoIcon className="postIcon" />
<span>Image</span>
</label>
<input
type="file"
accept=".png,.jpeg,.jpg"
onChange={(e) => setFile(e.target.files[0])}
id="file"
style={{ display: "none" }}
></input>
</div>
<button type="submit">Post</button>
</form>
然后使用multer和path將檔案值發送到此路由以上傳檔案夾public內的檔案夾影像
app.use("/images", express.static(path.join(__dirname, "public/images")));
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/images");
},
filename: (req, file, cb) => {
cb(null, req.body.name);
},
});
const upload = multer({ storage });
app.post("/upload", upload.single("file"), (req, res) => {
try {
return res.status(200).json("File uploaded successfully");
} catch (err) {
console.log(err);
}
});
但圖片沒有上傳
我試過什么
我使用file.originalName代替file.req.body為郵遞員測驗了路線,該路線確實有效,并且影像已成功上傳,我還檢查了資料物件中的值名稱和檔案,它成功地附加了它,我可以'不知道是什么問題,為什么它沒有通過react fetch請求上傳影像檔案?
uj5u.com熱心網友回復:
只需洗掉 JSON.stringify。并更改您的內容型別,如下例所示:
await fetch("http://localhost:8000/upload", {
headers: {
"Content-type": "multipart/form-data",
},
method: "POST",
body: data,
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/435186.html
