![](/img/trans.png)
[英]React: Multer image and data upload with using firebase function, node multer
[英]Multer Image Not loaded on Production Build React?
我正在使用 MERN 創建簡單的電子商務 我在生產模式下遇到錯誤。 文件上傳到指定文件夾,但不會在前端加載。
服務器.js
import path from 'path'
import express from 'express'
import dotenv from 'dotenv'
const __dirname = path.resolve()
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
)
} else {
app.get('/', (req, res) => {
res.send('Api running....')
})
}
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))
上傳路由和代碼
import path from 'path'
import express from 'express'
import multer from 'multer'
const router = express.Router()
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, '/uploads')
},
filename(req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
)
},
})
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/
const extName = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimeType = filetypes.test(file.mimetype)
if (extName && mimeType) {
return cb(null, true)
} else {
cb('Images only with jpg, jpeg, png ')
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb)
},
})
router.post('/', upload.single('image'), (req, res) => {
res.send(`/${req.file.path}`)
})
export default router
您的生產服務器不是用來存儲文件的,因為這會導致服務器資源消耗的增加。 因此它會自動刪除您上傳到生產服務器的任何文件/圖像。
以及為什么要將文件存儲在生產服務器上,只需使用數據庫或文件存儲系統(如 s3 存儲桶)。
我遇到了同樣的錯誤,我所做的只是將上傳文件夾的位置切換到頂部。 在構建前端請求任何圖像之前,您要確保所有圖像都可用。
import path from 'path'
import express from 'express'
import dotenv from 'dotenv'
const __dirname = path.resolve()
// Put it here
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
)
} else {
app.get('/', (req, res) => {
res.send('Api running....')
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.