类型错误:路径必须是字符串或缓冲区 MEAN 堆栈 [英] TypeError: path must be a string or Buffer MEAN stack

查看:59
本文介绍了类型错误:路径必须是字符串或缓冲区 MEAN 堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HTML 组件

 
<div class="form-group"><input type="file" class="form-control" formControlName="photo">

<button class="btn btn-default" type="submit">Sačuvaj</button></表单>

TS 组件

onSubmitPhoto() {this.profile.photo = this.form.value.photo;this.usersService.updatePhoto(this.profile, this.id).订阅(数据 =>{this.router.navigateByUrl('/');},错误 =>控制台错误(错误));}

服务

updatePhoto(profile: Profile, id: string) {const body = new FormData();body.append('照片', 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.json()).catch((错误:响应)=> {返回 Observable.throw(error.json());});}

Node.JS

 router.post('/photo/:id', (req, res) => {控制台日志(req.files);User.find({_id: req.params.id }).exec((err, user) => {如果(错误){返回 res.status(500).json({title: '发生错误',错误:错误});}user.img.data = fs.readFileSync(req.files);user.img.contentType = '图片/png';user.save((err, obj) => {如果(错误){抛出错误}console.log('成功')})});});

模型

const schema = new Schema({img:{ 数据:缓冲区,内容类型:字符串}});module.exports = mongoose.model('User', schema);

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

解决方案

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

接口配置文件{照片:文件;}更新照片(配置文件:配置文件,ID:字符串){const body = new FormData();body.append('照片',profile.photo);return this.http.post(`http://localhost:3000/profile/photo/${id}`, body,).map((响应:响应) => response.json()).catch((错误:响应)=> {返回 Observable.throw(error.json());});}

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

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

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

您可以使用 multerexpress-fileupload

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

const fileUpload = require('express-fileupload');router.use(fileUpload());//使用 express-fileupload 作为 multipart/form-data 编码的默认解析器router.post('/photo/:id', (req, res) => {User.find({_id: req.params.id }).exec((err, user) => {如果(错误){返回 res.status(500).json({title: '发生错误',错误:错误});}user.img.data = req.files.photo.data;user.img.contentType = '图片/png';user.save((err, obj) => {如果(错误){抛出错误}console.log('成功')})});});

I am using Angular 5 on front-end, Node on back-end and Mongo as the database. Now I am trying to save an image to the database but constantly getting this error. I can't figure out if I'm making mistake on front or back because this is my first time working with files. I did my research but it points mostly to angular 1.x.

HTML Component

  <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 Component

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

Service

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

Model

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

Any help is appreciated. Also, loging req.files returns undefined.

解决方案

To upload a file you need to wrapp it in a FormData instance as follows:

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

Furthermore, your backend is most likely failing in the following section:

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

Considering that you are now uploading a form with multipart/form-data encoding, you will need to use some middleware to parse the request in your backend as stated in the expressjs doc

You could use multer or express-fileupload

If you go with the second, you will need the following:

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

这篇关于类型错误:路径必须是字符串或缓冲区 MEAN 堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆