【发布时间】:2018-12-16 07:53:07
【问题描述】:
我有一个在本地运行的带有 Express 服务器的 Nodejs,允许我上传图像,我在 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 的发帖请求:
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
},
【问题讨论】:
标签: node.js express react-native image-uploading multer