我是一名有用的助手,可以为您翻译文本。
我有一个运行在本地的Nodejs服务器,使用Express框架,可以让我上传图片。我在Postman上没有问题地完成了上传,但当我尝试从React Native上传时,服务器会收到请求数据,包括图像,但不会将其上传到服务器!我在这里做错了什么,请看一下!
这是我的multer配置:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './server/uploads/');
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
}
})
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image') {
cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter,
});
这是我的路由调用:
route.post('/products', upload.single('image'), userAuthenticate, ProductController.createProduct);
这是我的控制器:
export const createProduct = async (req, res) => {
try {
console.log(req);
const { serial, name, description, cate_id, quantity, origin_price, sell_price, attributes } = req.body;
const newProduct = new Product({ serial, name, description, cate_id, quantity, origin_price, sell_price, attributes });
newProduct._creator = req.user._id;
// upload image
console.log(req.file);
newProduct.image = fs.readFileSync(req.file.path);
let product = await newProduct.save();
let user = req.user;
user._products.push(product);
await user.save();
return res.status(201).json({ product });
} catch (e) {
console.log(e.message);
return res.status(e.status || 404).json({ err: true, message: e.message });
}
}
这是来自React Native的我的POST请求:
const data = new FormData();
data.append('serial', serial);
data.append('name', name);
data.append('description', description);
data.append('sell_price', [{ 'value': sell_price }]);
data.append('origin_price', origin_price);
data.append('quantity', quantity);
data.append('cate_id', cate_id);
data.append('attr', attr);
data.append('image', {
uri: image.uri,
type: image.type,
name: image.name
});
let product = await axios({
method: 'POST',
url: 'http://localhost:3000/api/products',
data: data,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'x-auth': token,
}
})
这是我在产品模型中的图片字段:
image: {
type: Buffer
},