如何修复未知错误(空FormData文件)上载图像文件

时间:2019-06-05 03:51:35

标签: angular express

如果有人可以帮助我修复以下代码,该代码发送空的'FormData object to http / 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);
    }
  }
}

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

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

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

enter image description here

和服务器端日志记录:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是解决方案。最主要的是,按照@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);
    }
  }

后端数据模型(快速):

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"});
        });        
    },
];