[英]checking file size before uploading image using multer
在將圖像上傳到磁盤之前,如何使用與圖像傳遞相關的提交數據到服務器。這可能嗎? 如果沒有那么請給我另一個解決方案。
我想檢查文件的大小,它應該至少為 4mp 分辨率,如果它的分辨率更小,則不應上傳圖像並發送錯誤消息
exports.uploadimg=(req,res,next)=>{
uploadphoto(req, res, (err) => {
if (err) {
res.render("upload")
}
else {
res.send("photo uloaded")
}
})
我認為你有一些多部分中間件(比如connect-multiparty )讀取multipart/form-data
請求的請求有效負載。
該中間件會根據request
object ( request.files
) 為您提供files
object。 files
object 的屬性是每個文件上傳字段的鍵。 每個此類屬性的值可以是 object(單個文件上傳)或數組(多個文件上傳)。 嵌套在files
object 中的每個對象都有描述實際上傳文件的屬性,並允許您在以下中間件中運行您認為合適的檢查。
// router declarations const {Router} = require('express'); const multipart = require('connect-multipart'); const multipartMiddleware = multipart(); const validateFileSize = (file) => { /* Each file has the following property: fieldName - same as name - the field name for this file originalFilename - the filename that the user reports for the file path - the absolute path of the uploaded file on disk headers - the HTTP headers that were sent along with this file size - size of the file in bytes */ // check against file size if (file.size < 4 * 1024 * 1024) throw new Error('File is too small'); } const validateImageMiddleware = (req, res, next) => { // say we expected an upload field with key "productImage" const { files: { productImage } } = req; const isMultiple = Array.isArray(productImage); if (isMultiple) { productImage.forEach(validateFileSize); } else { validateFileSize(productImage); } // if we got here, the files were valid so we go to next handler next(); }; const myRouter = Router(); myRouter.post('/expect-file', multipartMiddleware, validateImageMiddleware, (req, res) => { // do whatever you want to do res.send('Success'); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.