首页 > 解决方案 > 如何修复未知错误(空 FormData 文件)上传图像文件

问题描述

如果有人可以帮我修复以下代码,它发送空的“FormData object tohttp/post”,我将不胜感激:

我在网上看了几天,但没有一个所谓的修复工作。

app.component.html

<input type="file" (change)="onSelectFile($event)" >
<button (click)="uploadFiles()">Upload</button>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  selectedFile: File; 

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  onSelectFile(event) {
    this.selectedFile = <File>event.target.files[0];
    console.log("File name: " + this.selectedFile.name);    
  }

  uploadFiles() {
    let fd = new FormData();

    fd.append('image', this.selectedFile, this.selectedFile.name);
    console.log("Uploading: " + JSON.stringify(this.selectedFile.name));
    try {
        this.http.post("http://localhost:3000/selection/test-photo",fd)
        .subscribe(
          (res) => {
            console.log("Successful response: " + res)},
          (err) => {
            console.log("Subscribe error: " + JSON.stringify(err))} 
      );
    }
    catch(e) {
      console.log("Caught error: " + e);
    }
  }
}

关于selection_controller.jsExpress 中的后端路由,我现在要做的就是记录http.post请求:

exports.selection_test_photo = [
    (req,res,next) => {
        console.log("Posting . . . ");
        console.log("Photos: " + util.inspect(req.body));
        res.json(req.body);
    }
];

这是运行后的客户端屏幕截图:

在此处输入图像描述

和服务器端日志记录:

在此处输入图像描述

标签: angularexpress

解决方案


这是解决方案。根据@Shashank Vivek 的建议,主要的是我需要multer在后端使用:

前端(角度):

uploadFiles() {
    let fd = new FormData();
    fd.append('image', this.selectedFile);
    fd.append('timeStamp', Date.now().toString());
    try {
        this.http.post("http://localhost:3000/selection/test-photo",fd)
        // this.http.post("http://localhost:3000/selection/test-photo",this.selectedFile)
        .subscribe(
          (res) => {
            console.log("Successful result: " + JSON.stringify(res))},
          (err) => {
            console.log("Subscribe error: " + JSON.stringify(err))} 
      );
    }
    catch(e) {
      console.log("Caught error: " + e);
    }
  }

后端数据模型(Express):

var PhotoSchema = new Schema (
    {
        timeStamp: {type: Object},
        photo: {data: Buffer, contentType: String}
    }
)

app.js

var multer = require('multer');

app.use(multer({ dest: './uploads/',
    rename: function (fieldname, filename) {
      return filename;
    },
  }
).single('image'));

照片上传路由回调函数:

var fs= require('fs');

exports.selection_test_photo = [
    (req,res,next) => {
        const photo = new Photo();
        photo.photo.data = fs.readFileSync(req.file.path);
        photo.photo.contentType = 'image/png';
        photo.timeStamp = {"value": req.body.timeStamp};
        photo.save(function(err){
            if (err) {return next(err)};
            res.json({"foo": "bar"});
        });        
    },
];



推荐阅读