Невозможно проанализировать multipart / form-data в express.Multer req.file поставляется как неопределенный - PullRequest
0 голосов
/ 16 января 2019

Я не могу разобрать multipart / form-data с помощью 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>
...