尝试发送formData时出现“ MulterError:意外字段”

时间:2019-02-19 12:01:57

标签: node.js reactjs axios multer

我正在尝试使用Axios将包含一个图像或一组图像的表单发送到Express API。尝试发送时,在Express上出现以下错误:

MulterError: Unexpected field

我正在使用React-Dropzone来获取文件。之后,我将通过状态获取所有表单数据,然后将对象转换为FormData()。 我尝试过在axios上使用以下配置,也可以不使用以下配置:     {标题:{'Content-Type':'multipart / form-data'}} 但是结果总是一样。

我的快递路线:

app.post('/adverts', requireAuth, upload.array('images'), Adverts.create);

我的multer配置(使用multer-s3):

const multer = require('multer');
const multerS3 = require('multer-s3');
const uuid = require('uuid/v1');
const aws = require('aws-sdk');

const s3 = new aws.S3({
    accessKey: process.env.AWS_ACCESS_KEY,
    secretAccesKey: process.env.AWS_SECRET,
    region: 'eu-west-1',
});

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: process.env.AWS_S3_IMG,
        acl: 'public-read',
        metadata: function(req, file, cb) {
            cb(null, { fieldName: file.fieldname });
        },
        key: function(req, file, cb) {
            cb(null, `${req.user.id}/${uuid()}`);
        },
    }),
});
module.exports = upload;

我的反应组件:

<form onSubmit={this.handleSubmit.bind(this)} encType="multipart/form-data">
    <TextField
        fullWidth
        label='title'
        value={this.state.title}
        onChange={e => this.setField('title', e)}
        type="text"
        required
        />
    <Dropzone onDrop={this.onDrop} accept=".png,.jpg,.jpeg" maxSize={5000000} name="images">
        {({ getRootProps, getInputProps, isDragActive }) => {
            return (
                <div className={classes.dropBox} {...getRootProps()}>
                    <input {...getInputProps()} />
                    {isDragActive ? <p>Drop...</p> : <p>Drag here and drop to upload</p>}
                 </div>
            );
        }}
    </Dropzone>
    <Button color="primary" variant="contained" type="submit">
        Create
    </Button>
</form>

表单handleSubmit函数:

handleSubmit = e => {
     e.preventDefault();
     const { title, images } = this.state;
     /* some validation */

     const formData = objectToFormData(values);
     api.post('/adverts', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(advert =>
          Router.push(`/ad/${advert.data.reference}`)
      );
}

onDrop函数,在用户添加图像时触发:

onDrop = files => {
    const images = this.state.images.concat(
        files.map(file =>
            Object.assign(file, {
                preview: URL.createObjectURL(file),
            })
        )
    );

    const totalsize = images.reduce((total, current) => {
        return total + current.size;
    }, 0);

    if (totalsize < 5000000) {
        this.setState({
            images,
            fileSize: (totalsize / 1e6).toFixed(2),
            filePercentage: (totalsize * 100) / 5000000,
        });
    }
};

1 个答案:

答案 0 :(得分:0)

代码中的错误是您正在发送单个图像,并且在接受时正在接受数组

尝试

app.post('/adverts', requireAuth, upload.single('image'), Adverts.create);