【发布时间】:2021-04-13 07:11:34
【问题描述】:
以下是文件上传的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'] { 错误号:-4058, 代码:'ENOENT', 系统调用:'打开', 路径:'D:\NodeE\public\product_images\5ff718bebe310d2f3c34590a\noimage.jpg' }
【问题讨论】:
-
在你的电脑里
D:\NodeE\public\product_images\5ff718bebe310d2f3c34590a\noimage.jpg存在吗? -
mkdirp()是异步的,您必须等待它完成才能将文件移动到其中,即将移动代码移动到then()回调中
标签: javascript node.js backend