[英]Cloudinary image size is 10 mb but unable to upload images of even 500 kb using node.js
[英]Unable to upload images to a specific folder in node.js using fileuploads
下面是用於文件上傳的 html
<div class="form-group" >
<label for="Image">Image</label>
<input type="file" name="image" value="<%=fillData.image%>" id="inpFile" class="form-control"placeholder="drop an image " /><br>
<div class="image-preview" style="text-align: center;">
<img src="" id="imgPreview" alt="imagePreview"/>
</div>
</div>
使用fileupload
模塊在 NodeJS 中處理圖像上傳的服務器端代碼
router.post("/addProduct",(req,res)=>{
const nimage = req.files.image.name
const Price = parseFloat(req.body.price).toFixed(2)
console.log(req.files.image)
const nProduct = new Products({
title:req.body.title,
slug:req.body.slug,
desc :req.body.description,
category:req.body.category,
price:Price,
image:nimage
})
nProduct.save().then((value) => {
mkdirp("public/product_images/"+nProduct._id).then(made=>{
console.log(`file created starting with on id ${made}`)
})
mkdirp("public/product_images/"+nProduct._id+"/gallery").then(made=>{
console.log(`file created starting with id and gallery ${made}`)
})
mkdirp("public/product_images/"+nProduct._id+"/gallery/thumbs").then(made=>{
console.log(`file created starting with and thumbs${made}`)
})
if(nimage!=""){
console.log("hello")
const productImage = req.files.image
const path = "public/product_images/"+nProduct._id+"/"+nimage;
console.log(path)
productImage.mv(path, function(err){
return console.log(err)
})
}
})
}
收到以下錯誤
[錯誤:ENOENT:沒有這樣的文件或目錄,打開 'D:\NodeE\public\product_images\5ff718bebe310d2f3c34590a\noimage.jpg'] { errno:-4058,代碼:'ENOENT',系統調用:'open',路徑:' D:\NodeE\public\product_images\5ff718bebe310d2f3c34590a\noimage.jpg' }
您正在同步使用 mkdirp,而它是異步操作。
將所有代碼移入then(made=>{... })
或使用異步等待。
router.post("/addProduct",async (req,res)=>{
const nimage = req.files.image.name
const Price = parseFloat(req.body.price).toFixed(2)
console.log(req.files.image)
const nProduct = new Products({
title:req.body.title,
slug:req.body.slug,
desc :req.body.description,
category:req.body.category,
price:Price,
image:nimage
})
await nProduct.save();
await mkdirp("public/product_images/"+nProduct._id);
await mkdirp("public/product_images/"+nProduct._id+"/gallery");
await mkdirp("public/product_images/"+nProduct._id+"/gallery/thumbs");
if(nimage!=""){
console.log("hello")
const productImage = req.files.image
const path = "public/product_images/"+nProduct._id+"/"+nimage;
console.log(path)
productImage.mv(path, function(err){
return console.log(err)
})
}
}
您需要鏈接then
,以便僅在創建目錄后才寫入目錄
例如。
mkdirp(...)
.then(made=>{
// write to directory here
})
或者,如果您想在創建所有目錄后編寫使用
Promise.all(mdirp('...'), mdirp('...'), mdirp('...'))
.then(made=>{
// write to directory here
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.