类型错误:路径必须是字符串或缓冲区 MEAN 堆栈

2024-01-03

我在前端使用 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)
  );
}

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

任何帮助表示赞赏。 此外,记录 req.files 返回未定义。


要上传文件,您需要将其包装在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 文档 http://expressjs.com/de/api.html#req.body

你可以使用multer https://www.npmjs.com/package/multer or 快速文件上传 https://www.npmjs.com/package/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')
        })
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:路径必须是字符串或缓冲区 MEAN 堆栈 的相关文章

随机推荐