我想我應該使用 fs 但我不太確定如何使用
ejs:
<form action="/products" method="POST">
<input type="file" name="image" id="image">
<button class="submit">Submit</button>
</form>
應用程式.js
app.post('/products', (req, res) => {
console.log(req.body)
console.log(req.body.image) //console logs a string
fs.writeFile('./image.png', req.body.image, (err) => {
if (err) throw err;
console.log('saved!');
});
res.render('products', { title: 'bib' })
})
但它不起作用,因為它回傳的是字串而不是檔案,正如我所說,我想使用 fs 在本地保存檔案
uj5u.com熱心網友回復:
請參閱MDN 上的表單元素:
enctype如果method屬性的值為post,enctype就是表單提交的MIME型別。可能的值:
- application/x-www-form-urlencoded:默認值。
- multipart/form-data:如果表單包含 type=file 的元素,則使用此選項。
你沒有設定<form enctype="multipart/form-data">所以瀏覽器不會上傳資料。
您的服務器端代碼缺少添加正文決議中間件的部分,但如果它支持您擁有的表單,那么它適用于 URL 編碼的表單資料,而不是多部分表單資料。
您需要一個可以處理您正在使用的資料格式的正文決議器。
Express 與body-parser打包在一起,它不支持多部分形式的正文,但建議了許多選項。
這不處理多部分物體,因為它們復雜且通常很大。對于多部分正文,您可能對以下模塊感興趣:
- busboy 和 connect-busboy
- 多方和連接多方
- 強大
- 穆爾特
Multer可能是其中最受歡迎的。
你需要類似的東西:
app.post('/products', upload.single('image'), (req, res) => {
… 其中upload由 Multer 提供,image是name檔案輸入的。然后,您可以通過 訪問影像req.file。
uj5u.com熱心網友回復:
您可以嘗試使用multerwhich is 來快速上傳檔案。
const multer = require('multer')
const upload = multer({
dest: 'path to where ever you want it to be saved locally in the server, eg ./images',
}) // the middleware
app.post('/products', upload.single('image'), (req, res) => {
console.log(req.body)
console.log(req.body.image) //console logs a string
fs.writeFile('./image.png', req.body.image, (err) => {
if (err) throw err;
console.log('saved!');
});
res.render('products', { title: 'bib' })
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493472.html
標籤:javascript html 节点.js 图片 fs
