无法在MEAN-stack应用中上传图像

时间:2018-03-22 19:39:59

标签: javascript node.js angular mean-stack

所以我有一个平均堆栈应用程序。在用户的个人资料页面上,我希望他们能够上传图片。

现在,我首先在模板中选择它,然后通过组件到达服务文件,在那里我使用formData发出POST请求。在后端我使用 Multer 中间件来处理上传,但这里出了点问题。以下是我在后端的代码。

var multer  = require('multer')
var upload = multer({ dest: '../public/uploads/' });

router.post('/uploadProfilePicture/:userId', upload.single('avatar'), function(req, res){
    console.log('entered');
    console.log(req.file);
    console.log(req.body);
    res.status(200).json({
        msg: 'guuud'
    })
});

我大多只是想检查一下是否到达了后端。控制台给我以下错误:

  

POST / user / uploadProfilePicture / 5aaf1b7c18f2aa3d88e3b59e 500 16.382 ms    - 1711

没有输入的控制台日志,也没有其他控制台日志。服务和后端之间出了问题,但我完全不知道。

以下是用于此次上传的服务和其他文件。

Service.component.ts

postFile(fileToUpload: File, userId) {
        const formData: FormData = new FormData();
        console.log(fileToUpload);
        formData.append('fileKey', fileToUpload, fileToUpload.name);
        console.log(formData);

        return this.http.post("http://localhost:3200/user/uploadProfilePicture/" + userId, formData)
            .map(() => { return true; })
            .catch((e) => this.handleError(e));
    }

这是页面+服务文件中console.logs的结果

enter image description here

profile.component.ts

handleFileInput(files: FileList){
    this.fileToUpload = files.item(0);
    this.uploadFileToActivity();
}

uploadFileToActivity() {
    this.userService.postFile(this.fileToUpload, localStorage.getItem('userId')).subscribe(data => {
        console.log(data)
    }, error => {
        console.log(error);
    });
}

profile.component.html

<div class="col-md-8 col-md-offset-2 profilePicSection">
        <div class="form-group">
            <label for="file">Choose File</label>
            <input type="file"
                   id="file"
                   (change)="handleFileInput($event.target.files)">
        </div>
    </div>

编辑:我的服务器控制台给出的错误:

Error: Unexpected field
    at makeError (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-error.js:12:13)
    at wrappedFileFilter (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\index.js:40:19)
    at Busboy.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (events.js:159:13)
    at Busboy.emit (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\types\multipart.js:213:13)
    at PartStream.emit (events.js:159:13)
    at HeaderParser.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (events.js:159:13)
    at HeaderParser._finish (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:40:12)
    at SBMH.emit (events.js:159:13)
    at SBMH._sbmh_feed (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:159:14)
    at SBMH.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:56:14)
    at HeaderParser.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:46:19)
    at Dicer._oninfo (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:197:25)

1 个答案:

答案 0 :(得分:0)

我将此代码用于视频类型文件,它工作正常,希望它可以帮助您

var storage = multer.diskStorage({
    destination: function (req, file, callback) {

            var fileDest = path.join('../uploads/');
            if (!fs.existsSync(fileDest)) {
                mkdirp(fileDest, function (err) {
                    if (err) {
                        logger.error(err);
                        callback(err, false);
                    } else {
                        callback(null, '../uploads');
                    }
                });
            } else {
                callback(null, '../uploads/');
            }

    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '.' + file.originalname.split('.')[1]);
    }
});

var upload = multer({
    storage: storage,
    fileFilter: function (req, file, callback) {

        // To reject this file pass `false`, like so:
        var sw = 0;
        for (var i = 0; i < config.videoMimeTypes.length; i++) {
            if (file.mimetype === config.videoMimeTypes[i]) {
                sw = 1;
                break;
            }
        }
        if (sw === 0) {
            logger.error('Not allowed file type sent');
            // return callback(new Error('Only video files are allowed!'));
            return callback('Only video files are allowed!', false);
        }

        // To accept the file pass `true`, like so:
        callback(null, true);

    },
    limits: {
        fileSize: config.maxUploadSize
    }
});

app.post('/upload', upload.any(), router.uploader);