如何修补multer文件名


const multerStorage = multer.diskStorage({
destination: (req, file, cb) =>{
cb(null, '../client/public/uploadImg' )
},
filename :  (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + '_' + file.originalname)
}

})

一旦我为我的文件指定了一个唯一的名称,并保存在uploadImg文件夹中,现在我需要获取文件名,这样我就可以在客户端上进行fatch

{usrs.map((alldata, i)=>(
<div key={i} >
<img src={`/uploadImg/${alldata.photo}`} alt="..." />
<h1> {alldata.name}</h1>
<h3> {alldata.photo} </h3>
</div>
))}

在某个时刻,您的客户端正在发出一个HTTP请求(我认为这是一个Ajax请求(来上传图像。

这将由一些服务器端代码来处理。以下是文档中的示例:

const multer  = require('multer')
const upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
// req.file is the name of your file in the form above, here 'uploaded_file'
// req.body will hold the text fields, if there were any 
console.log(req.file, req.body)
});

您需要在对Ajax请求的响应中发送req.file的值(或者更确切地说是从中派生的URL(。

由于您的客户端代码使用的是JSX,我假设您使用的是React.js.

客户端代码需要注意该响应,并将结果存储在状态中。

然后,可以在渲染组件时从状态中读取值。

最新更新