【问题标题】:How to send image from Angular to Node JS using express and multer?如何使用 express 和 multer 将图像从 Angular 发送到 Node JS?
【发布时间】:2019-01-28 12:48:58
【问题描述】:

我在谷歌上搜索了几个小时以找到解决方案,但我的项目没有任何效果。我想要一个可以从 Angular 发送图像并将它们存储在 Node JS 目录中的模块。

我知道有什么问题,因为 req.file 总是未定义...

这是我的 Node JS 代码:

const express = require('express');
const app = express();
const multer = require('multer');
const bodyParser = require('body-parser');

const upload = multer({
    dest: 'assets/' // this saves your file into a directory called "uploads"
  });

app.use(express.static('assets'));

app.use(bodyParser.json());

var cors = require('cors')
app.use(cors())

  app.route(requestPath).post((req, res) => {
    upload.single('image')
    console.log(req.file);
});

我的 Angular 服务:

  addImage( ... , fd){ 
    return this.http.post(requestPath, {
  file: fd 
})

}

我的角码:

selectedFile = null;

imageSelected(event){
    this.selectedFile = event.target.files[0];
  }

onSubmit(){
    const fd = new FormData();
    fd.append('image', this.selectedFile, this.selectedFile.name);
    this.imageService.addImage( ... , fd).subscribe( _ => {
        this.router.navigate(['../'], { relativeTo: this.route });
      });
    }

我的 HTML 代码:

    <form class="form-horizontal" role="form" [formGroup]="addImage" (ngSubmit)="onSubmit()" id="uploadForm" enctype="multipart/form-data">
        <div class="form-group">
          <label class="col-lg-3 control-label">Choisissez la photo</label>
          <input type="file" id="image" name="image" class="form-control" formControlName="photo" (change)="imageSelected($event)" required>
        </div>

如果有人可以帮助我,非常感谢! 我正在做一个照片库,但是如果我不能上传照片就没有用了...

【问题讨论】:

    标签: node.js angular express multer


    【解决方案1】:

    尝试(在 Node 中)记录 req.body.file:

      app.route(requestPath).post((req, res) => {
        upload.single('image')
        console.log(req.body.file);
    

    此外,在 Angular 服务中,定义 FormData 变量后,将文件和 file.name 变量注销到控制台,以确保您有数据可以在服务中发送。这将告诉您问题是在前端还是在 Node 端。

    const fd = new FormData();
    
    console.log("this.selectedFile",this.selectedFile;
    console.log("this.selectedFile.name", this.selectedFile.name);
    
    fd.append('image', this.selectedFile, this.selectedFile.name);
    

    【讨论】:

    • 感谢您的回答! req.body.file 的日志是 {} 并且前面的日志看起来不错,第一个显示文件的内容,第二个显示正确的名称。我真的不明白问题出在哪里......
    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2021-02-04
    • 2020-11-29
    • 1970-01-01
    • 2020-10-10
    • 2021-04-16
    • 2014-04-17
    相关资源
    最近更新 更多