最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

TypeError:path必须是字符串或Buffer MEAN堆栈

运维笔记admin8浏览0评论

TypeError:path必须是字符串或Buffer MEAN堆栈

TypeError:path必须是字符串或Buffer MEAN堆栈

我在前端使用Angular 5,在后端使用Node,使用Mongo作为数据库。现在我试图将图像保存到数据库,但不断收到此错误。我无法弄清楚我是在前面或后面犯错,因为这是我第一次使用文件。我做了我的研究,但它主要指向角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。

回答如下:

要上传文件,您需要将其包装在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中所述

你可以使用multer或express-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')
        })
    });
});
发布评论

评论列表(0)

  1. 暂无评论