我使用Multer上传照片。。它可以在邮递员中工作,并且可以成功上传照片,但是当我通过redux形式将其上传时。.它引发错误“ TypeError:无法读取未定义的属性'filename'” 这意味着req.file是未定义的
这是我在路由器中的Multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+'.png')
//cb(null, "atofile")
},
limits: {
fileSize: 2000000
},
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(png|jpg)$/)) {
return cb(new Error('Please upload a photo png or jpg'))
}
cb(undefined, true)
}
})
var upload = multer({ storage: storage })
router.post('/api/add/product',[auth , upload.single('upload') ] , async (req, res) => {
const product = new Product({
...req.body,
})
let imgUrlPath = 'imgs/' +req.file.filename
product.imgURLs = product.imgURLs.concat({imgURL: imgUrlPath})
try {
await product.save()
res.status(201).send({product})
} catch (e) {
res.status(400).send(e)
}
})
module.exports = router
这是我的redux表单,在发送json数据时效果很好
<form onSubmit={handleSubmit(this.onSubmit)}>
<fieldset>
<Field
type='text'
name='nameAr'
id='nameAr'
className='nameAr'
// placeholder='enter title in Arabic'
component={InputForm}
label='Title in Arabic'
/>
</fieldset>
<fieldset>
<Field
type='text'
name='nameEn'
id='nameEn'
className='nameEn'
// placeholder='enter title in English '
component={InputForm}
label='Title in English'
/>
</fieldset>
<fieldset>
<Field
type='file'
name='upload'
id='upload'
className='imgURL'
// placeholder='enter title in English '
component={InputFile}
//change={this.onChangeHandler}
label='Pic'
/>
</fieldset>
<button type="submit" class="custum-btn-form">
submit</button>
</form>
这是我以形式使用的输入组件
import React, { Component } from 'react';
import InputCss from './inputAdminForm.scss';
export default class CustomInput extends Component {
constructor(props) {
super(props)
this.onChange = this.onChange.bind(this)
}
onChange(e) {
const { input: { onChange } } = this.props
onChange(e.target.files[0])
}
render() {
const { input: { value, onChange } } = this.props;
return (
<div className="form-group-admin">
<label htmlFor={ this.props.id } className="label-input-admin">{ this.props.label }</label>
<input
name="upload"
id={ this.props.id }
/* placeholder={ this.props.placeholder } */
className="inputText-admin"
type='file'
onChange={this.onChange}
required
/>
</div>
);
}
}
这是提交功能,当我console.log json.stringify(formData)时,我实际上看到带有文件对象的上传密钥
async onSubmit(formData) {
const { addProductToServer } = this.props;
await addProductToServer(formData,AdminToken)
}
这是由axios发出请求的动作功能
export const addProductToServer = (data, adminToken) => {
return async dispatch => {
dispatch({
type: ADDING_PRODUCT
});
try {
const response = await axios.post('/api/add/product', data, {
headers : { Authorization: `Bearer ${adminToken}`
} });
dispatch({
type: ADDED_TO_SERVER
});
} catch(err) {
dispatch({
type: ADDED_TO_SERVER_ERROR,
error: err.response.data.error
})
}
};
}