【问题标题】:Image upload from Angular 5 to Node.Js server图片从 Angular 5 上传到 Node.Js 服务器
【发布时间】:2018-08-27 22:50:30
【问题描述】:

我正在创建一个网站并使用 node.js 服务器来存储图像。我已经设置了服务器和网站,但是当我的发布请求似乎没有发送图像时。服务器检测到发布请求但没有收到图像。我是 node.js 和云计算的新手。 谢谢!

Angular 中的 post 请求:

constructor(private httpClient: HttpClient) { }
    selectedFile: File = null;
    onFileSelected(event) {
        this.selectedFile = <File>event.target.files[0];
        console.log(event);
        console.log(this.selectedFile);
    }
    onUpload() {
    const fd = new FormData();
    fd.append('image', this.selectedFile, this.selectedFile.name);
    this.httpClient.post('ip:port/header',
      {
        'message': 'Handling POST requests to /images',
        'createdImage': {
          'name': 'name',
          'size': 'size',
          'imageFile': this.selectedFile
        }
      })
      .subscribe(
        (response) => {
          console.log(response);
          console.log(fd);
        },
        (error) => {
          console.log(error, fd);
        });
    console.log(this.selectedFile);
  }
}

Node.js 发布请求处理程序:

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname);
    }
});

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        cb(null, true);
    } else {
        cb(null, false);
    }
};

const upload = multer({
    storage: storage,
    limits:{
        fileFilter: fileFilter
}});


router.post('/', upload.single('imageFile'),(req, res, next) => {
    console.log(req.file);
    const image = {
        //attributes of item that server will request (more important for db
        name: req.body.name,
        size: req.body.size,
        imageFile: req.body.imageFile

    };

    res.status(201).json({
        message: 'Handling POST requests to /images,',
        createdImage: image
    });
});

【问题讨论】:

  • this.selectedFile 是 HTML 文件输入元素吗?查看developer.mozilla.org/en-US/docs/Web/API/FormData/… 获取示例。
  • 嗨,对不起,我应该在那部分,我在 Angular 代码的顶部添加了 selectedFile 代码
  • 我不知道那里的“httpClient”是什么,但看起来你正在构建FormData 对象,然后不要将它传递给this.httpClient.post 方法。也许检查stackoverflow.com/a/47277805/6352710 - 看起来情况非常相似,即使用FormData 对象附加您想要的任何数据,然后将该对象传递给this.httpClient.post 方法。

标签: node.js image-uploading angular5 multer


【解决方案1】:

您必须将创建的 FormData 对象作为 POST 请求的主体传递,因为您需要将图像作为多部分类型发送。

您还需要更改fd.append('imageFile', ...); 以在后端获取文件,因为此名称必须与upload.single 方法的第一个参数匹配。

【讨论】:

    猜你喜欢
    • 2011-11-18
    • 2018-05-17
    • 2014-06-08
    • 2012-02-19
    • 1970-01-01
    • 2014-10-01
    • 2011-06-01
    相关资源
    最近更新 更多