【问题标题】:TypeError: path must be a string or Buffer MEAN stackTypeError: path must be a string or Buffer MEAN stack
【发布时间】:2018-06-07 12:58:05
【问题描述】:

我在前端使用 Angular 5,在后端使用 Node,并使用 Mongo 作为数据库。现在我正在尝试将图像保存到数据库但不断收到此错误。我不知道我是在正面还是背面犯错,因为这是我第一次处理文件。我做了我的研究,但它主要指向 angular 1.x。

HTML 组件

  <form [formGroup]="form" (ngSubmit)="onSubmitPhoto()">
    <div class="form-group">
      <input type="file" class="form-control" formControlName="photo">
    </div>
    <button class="btn btn-default" type="submit">Sačuvaj</button>
  </form>

TS 组件

onSubmitPhoto() {
this.profile.photo = this.form.value.photo;
this.usersService.updatePhoto(this.profile, this.id)
  .subscribe(
  data => {
    this.router.navigateByUrl('/');
  },
    error => console.error(error)
  );
}

服务

updatePhoto(profile: Profile, id: string) {
    const body = new FormData();
    body.append('photo', profile.photo);
    const headers = new Headers({ 'Content-Type': 'application/json' });
    return this.http.post('http://localhost:3000/profile/photo/' + id, body, { headers: headers })
        .map((response: Response) => response.json())
        .catch((error: Response) => {
            return Observable.throw(error.json());
        });
}

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);
        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);

感谢任何帮助。 此外,记录 req.files 会返回 undefined。

【问题讨论】:

  • 你不能序列化一个 File 对象

标签: node.js mongodb angular express angular5


【解决方案1】:

要上传文件,您需要将其包装在 FormData 实例中,如下所示:

interface Profile {
   photo: File;
}

updatePhoto(profile: Profile, id: string) {
    const body = new FormData();
    body.append('photo',profile.photo);
    return this.http.post(`http://localhost:3000/profile/photo/${id}`, body,)
        .map((response: Response) => response.json())
        .catch((error: Response) => {
            return Observable.throw(error.json());
        });
}

此外,您的后端很可能在以下部分失败:

user.img.data = fs.readFileSync(req.body.photo);

考虑到您现在正在上传带有multipart/form-data 编码的表单,您将需要使用一些中间件来解析后端中的请求,如expressjs doc 中所述

您可以使用multerexpress-fileupload

如果您选择第二个,您将需要以下内容:

const fileUpload = require('express-fileupload');

router.use(fileUpload());// use express-fileupload as default parser for multipart/form-data encoding

router.post('/photo/:id', (req, res) => {
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 = req.files.photo.data;
        user.img.contentType = 'image/png';
        user.save((err, obj) => {
            if (err) {
                throw err
            }
            console.log('success')
        })
    });
});

【讨论】:

  • 你确定可以通过req对象的body属性访问上传的文件吗?更新了我的答案
  • 更新了我的答案
  • 我已经在使用“express-fileupload”了。它仍然会抛出错误:无法读取未定义的属性“照片”
  • 请使用该信息和您的 node.js 版本更新您的问题
  • 我一直在做其他事情,我现在将更新,我设法将照片发送到后端,但遇到另一个错误
猜你喜欢
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2016-10-10
  • 1970-01-01
  • 2016-11-13
相关资源
最近更新 更多