TypeError:路径必须是字符串或Buffer MEAN堆栈 [英] TypeError: path must be a string or Buffer MEAN stack

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

问题描述

我在前端使用Angular 5,在后端使用Node,将Mongo用作数据库.现在,我试图将图像保存到数据库中,但不断出现此错误.我不知道是在前面还是在后面出错,因为这是我第一次使用文件.我进行了研究,但主要指向1.x角度.

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组件

  <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会返回未定义的内容.

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

推荐答案

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

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

考虑到您现在正在上传具有multipart/form-data编码的表单,您将需要使用一些中间件来按照

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

您可以使用 multer 如果您选择第二种,则需要以下内容:

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

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

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