當我進行多個上傳時它作業正常,但是當我上傳單個檔案時它不起作用。它說TypeError: req.body.file.map is not a function
我不知道這里發生了什么。是因為我已經映射了 req.body 嗎?
exports.create = (req, res) => {
const { name, description, price, category, quantity, url } = req.body
if (!name || !description || !price || !category || !quantity ) {
return res.status(400).json({
error: "All fields must be filled"
})
}
req.body.images = req.body.file.map(function (obj) {
const id = mongoose.Types.ObjectId();
return {
url: obj,
id: id,
isApproved: false,
};
});
req.body.shop = req.params.shopId;
let product = new Product(req.body);
var product_images = req.files;
var arrayofId = product_images.map(function (obj) {
return obj.id;
})
product.save((err, result) => {
if (err) {
return res.status(400).json({
error: `Error on saving product: ${dbErrorHandler(err)}`
});
}
connection.db.collection("productimage.files", function(err, collection){
if (err) {
return res.status(400).json({
error: `Error on saving image: ${dbErrorHandler(err)}`
});
}
collection.updateMany({
_id:
{
$in: arrayofId
}
}, {
$set: { aliases: [result._id.toString()] }
});
});
res.json(result);
});
};
這是我的上傳產品
export const addProduct = async (productData, shopId, url) => {
const ls = new SecureLS({ encodingType: "aes" });
const token = ls.get("token");
const formdata = new FormData();
for (let index = 0; index < productData.images.length; index ) {
formdata.append("file", productData.images[index]);
}
formdata.append("category", productData.category);
formdata.append("name", productData.name);
formdata.append("quantity", productData.quantity);
formdata.append("price", productData.price);
formdata.append("description", productData.description);
formdata.append("ingredients", productData.ingredients);
formdata.append("url", url);
return await fetch(`${API}/product/${shopId}`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: formdata,
})
.then((response) => {
return response;
})
.catch((err) => {
//console.log(err)
return err;
});
};
我也希望能夠上傳單個檔案。
uj5u.com熱心網友回復:
這是因為當您上傳單個檔案時,req.body.file它不是陣列。
在您的上傳功能中:
for (let index = 0; index < productData.images.length; index ) {
formdata.append("file", productData.images[index]);
}
你應該改為
for (let index = 0; index < productData.images.length; index ) {
formdata.append("file[]", productData.images[index]);
}
uj5u.com熱心網友回復:
當您上傳多個檔案時,它會變成一個陣列,并且您的地圖功能可以完美運行。但是當你上傳一個檔案時,它不是一個陣列,你會得到這個陣列。map 是一個陣列函式。
例如:
let req = {body: {
file: []
}};
req.body.file.map(x=>something);
上述功能將完美運行,但如果你這樣做
let req = {body: {
file: "value"
}};
req.body.file.map(x=>something);
這將通過錯誤“req.body.file.map 不是函式”
解決方案 從客戶端發送陣列中的檔案資料,即使單個檔案或檢查檔案是否是陣列,應用映射否則處理這個單個檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451604.html
