error Path必须是没有空字节的字符串

时间:2017-12-27 14:14:10

标签: node.js mongodb angular express

我想将前端的Angular图像上传到MongoDB。我设法将照片发送到后端,但在使用 fs.readFileSync 时出现此错误。

HTML组件

<input #fileInput type="file" />
<button (click)="addFile()">Add</button>

TS组件

 addFile(): void {
  let fi = this.fileInput.nativeElement;
   if (fi.files && fi.files[0]) {
   let fileToUpload = fi.files[0];
    this.usersService
    .upload(fileToUpload, this.id)
    .subscribe(res => {
      console.log(res);
    });
  }
 }

服务

upload(fileToUpload: any, id: string) {
    let input = new FormData();
    input.append("file", fileToUpload);
    return this.http.post('http://localhost:3000/profile/photo/' + id,input);
 }

Node.js的

router.post('/photo/:id', (req, res) => {
console.log(req.files);
User.find({ _id: req.params.id })
    .exec((err, user) => {
        if (err) {
            return res.status(500).json({
                title: 'An error occured',
                error: err
            });
        }
        user.img.data = fs.readFileSync(req.files.file.data);
        user.img.contentType = 'image/png';
        user.save((err, obj) => {
            if (err) {
                throw err
            }
            console.log('success')
        })
    });
});

猫鼬模型

const schema = new Schema({
  img: { data: Buffer, contentType: String}
});
module.exports = mongoose.model('User', schema);

CONSOLE.LOG(req.files)

>{file:
> { name: '2017-11-30 11_45_17-500px Blog » The passionate photographer community.50 Creative Self-Portrait Ide.png',
>   data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 de 00 00 03 84 08 06 00 00 00 96 f6 36 7a 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... >,
>   encoding: '7bit',
>   mimetype: 'image/png',
>   mv: [Function: mv] } }

感谢任何帮助。

0 个答案:

没有答案