簡體   English   中英

使用 multer、reactjs、nodejs 上傳圖片

[英]image upload using multer, reactjs, nodejs

 // nodejs const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, "images"); }, filename: (req, file, cb) => { cb(null, req.body.name); }, }); const upload = multer({ storage: storage }); app.post("/api/upload", upload.single("file"), (req, res) => { res.status(200).json("File has been uploaded"); }); app.listen(5000, () => { console.log("server running..."); }); // reactjs const [file, setFile] = useState(""); const handleChange = (e) => { setFile(e.target.files[0]); }; const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(); formData.append("name", file); try { const res = await axios.post("/api/upload", formData, { headers: { "Content-Type": "multipart/form-data", }, }); } catch (err) { console.log(err); } }; // jsx <form onSubmit={handleSubmit}> <input type="file" name="file" onChange={handleChange} /> <input type="submit" value="send" /> </form>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

您好,請問我在使用 react 運行此代碼時遇到問題,它使用 postman 可以完美運行,但在使用 react "POSThttp://localhost:3000/api/upload [HTTP/1.1 500 Internal Server Error 116ms]"時出現此錯誤,我在客戶端 package.json 文件上添加了“代理”:“http://localhost:5000”,我還同時使用來運行 nodejs 服務器和反應應用程序

這是來自節點的錯誤

MulterError: Unexpected field
[0]     at wrappedFileFilter (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\multer\index.js:40:19)
[0]     at Busboy.<anonymous> (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\multer\lib\make-middleware.js:114:7)
[0]     at Busboy.emit (events.js:315:20)
[0]     at Busboy.emit (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\busboy\lib\main.js:38:33)
[0]     at PartStream.<anonymous> (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\busboy\lib\types\multipart.js:213:13)
[0]     at PartStream.emit (events.js:315:20)
[0]     at HeaderParser.<anonymous> (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\dicer\lib\Dicer.js:51:16)
[0]     at HeaderParser.emit (events.js:315:20)
[0]     at HeaderParser._finish (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\dicer\lib\HeaderParser.js:68:8)
[0]     at SBMH.<anonymous> (C:\Users\Acer\Desktop\nodejs\imageupload\node_modules\dicer\lib\HeaderParser.js:40:12)

從 Axios 請求中刪除 header。

const res = await axios.post("/api/upload", formData);

因為在后端您使用的是upload.single("file") ,所以在客戶端中,您應該更改為:

    formData.append("file", file); // instead of formData.append("name", file);

另一種解決方案是使用 Postman 生成的代碼,如果您在此工具中有正確的結果。 按鈕 </> 位於右側欄上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM