我嘗試制作一個應該將檔案提交到快速后端的表單,但由于某種原因在后端,我在提交表單時沒有收到資料。
在使用console.log我{}得到 req.body和sampleFileundefined
這是html表單,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="./styles/styles.css" />
<title>Upload </title>
</head>
<form
ref="uploadForm"
name='uploadForm'
id="uploadForm"
action="http://localhost:4000/partners"
method="post"
encType="multipart/form-data">
<input
id="upload" type='file' name="input1"
placeholder="Upload file" />
<button type="submit">Submit</button>
</form>
</body>
</html>
這是處理 post 請求的快速后端路由,
import express from 'express'
const app = express()
app.use(express.urlencoded({extended: true}))
app.post('/partners', async function (req, res) {
console.log(req.body, '>>>>>>>body')
console.log(req.files, '>>>>>>>files')
})
app.listen(4000, () => console.log('Server running on port 4000'))
uj5u.com熱心網友回復:
要處理檔案上傳,您需要 Express 的多部分編碼器。您可以為此使用Multer中間件庫。
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/partners', upload.single('partner'), function (req, res, next) {
// req.file is the `partner` file
// req.body will hold the text fields, if there were any
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521277.html
