无法解析express中的multipart / form-data.Multer req.file即将如期定义

时间:2019-01-16 04:56:35

标签: javascript node.js express multer body-parser

我无法使用express,bodyparser和multer解析多部分/表单数据。 请求参数未定义。试图通过多种解决方案。还是没有运气

req.uploadFileName is undefined.
console.log('Upload file...' + req.file); //undefined
console.log('Upload file...' + req.files); //undefined
console.log('Upload uploadFileName...' + req.uploadFileName); //undefined
console.log('Upload  body' + req.body) //undefined

NPM软件包

  • “ multer”:“ ^ 1.4.1”
  • “表达”:“ ^ 4.16.3”
  • “ body-parser”:“ ^ 1.18.3”

    router.post('/',uploadService.getUpload(),uploadService.uploadFile);

        export const uploadFile = (req, res, next) => {
        console.log('Upload file...' + req.file);
        console.log('Upload file...' + req.files);
        console.log('Upload uploadFileName...' + req.uploadFileName);
        console.log('Upload  body' + req.body);
    
        let file = req.uploadFileName;
        console.log('Upload fileName' + req.body.uploadFileName);;
        if (file) {
            uploadImageToStorage(file).then((fileURL) => {
                res.json({
                    status: 'success',
                    fileURL: fileURL
                });
            }).catch((error) => {
                console.error(error);
                next('failed to upload file ', error)
            });
        } else {
            console.error('failed to upload file ', file);
            next('failed to upload file ', file)
        }
    };
    
    export const getUpload = () => {
        // no larger than 5mb, you can change as needed.
        const multer = Multer({
            storage: Multer.memoryStorage(),
            limits: {
                fileSize: 5 * 1024 * 1024;
            }
    
        });
        return multer.single('uploadFileName')
    }
    

代码上传文件: index.html

<form class="uploadForm" action="/api/v1/upload" method="post" enctype="multipart/form-data">
    <label class="control-label">Select File</label>
    <input name="uploadFileName" id="input-1" type="file" class="file">
    <input type="submit" value="submit" />
</form>

0 个答案:

没有答案