如何将文件从angular7上传到Node.js服务器

时间:2019-04-11 11:15:42

标签: node.js angular

我的node.js代码在Postman中100%工作, 但是当我发送FormData时出现角度,服务器中什么也没有发生,没有错误,但文件未上传。 如何按角度上传文件?

HTML组件:

<form>
  <input type="file" (change)="OnFileSelected($event)" name='photo'>
  <button type='submit' (click)="OnUpload()">Save Post</button>
</form>

Ts组件:

OnFileSelected(event){
  this.SelectedFile = event.target.files[0] as File;
}
OnUpload(){
  const form: FormData = new FormData();
  form.append('photo', this.SelectedFile, this.SelectedFile.name);
  //Convert to Json because 'Unexpected token - in JSON at position 0 at JSON.parse' error in server
  let responseBody: {} = JSON.stringify(form);
  this.http.post(URL, responseBody).subscribe(event => { console.log(event)}, err => {console.log(err)
    });
  }

Node.js服务器:

const path = require('path');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')
const router = express.Router();
const DIR = './uploads';
let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});
let upload = multer({ storage: storage });
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});
router.post('/upload-image', upload.single('photo'),  async function (req, res) {
  console.log(req.body);
  if (!req.file) {
    console.log("No file received");
    return res.send({
      success: false
    });
  } else { 
    console.log('file: ',req.file);
    return res.send({
      success: true
    })
  }
});

3 个答案:

答案 0 :(得分:0)

您需要指定您的请求是表单数据请求:

// Create Form Data
const formData: FormData = new FormData();
formData.append('photo', this.SelectedFile, this.SelectedFile.name);

// Create options for the request
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'multipart/form-data', //     <-- IMPORTANT
    'Accept': 'application/json'
  })
};

this.http.post(URL, formData, httpOptions).subscribe(...)

答案 1 :(得分:0)

您需要先在OnInit()中实例化文件,然后在完成的OnUpload()函数中创建实例:

            ngOnInit() {
this.form = new FormGroup({
  photo: new FormControl(null, {
    validators: [Validators.required]}) }

您可以根据需要删除验证器,也可以像这样编辑onFileSelected()函数:

this.SelectedFile = event.target.files[0] as File;   

this.form.patchValue({ photo: file });
this.form.get('photo').updateValueAndValidity();
const reader = new FileReader();
reader.readAsDataURL(file);
console.log(file);

这样调用您的函数:

onUploadFile(event: Event){}

答案 2 :(得分:0)

有很多方法可以将文件传输到服务器,如果是常见情况,那么我建议使用Dropzone.js角度包装器。 最好将Dropzone的所有自定义配置都包含一个自定义角度组件,以满足您的需求。

使用它也很容易,一旦安装了软件包,文件输入就很简单:

<dropzone [config]="config" [message]="'Click or drag images here to upload'"

(error)="onUploadError($event)" (success)="onUploadSuccess($event)"></dropzone>

文档可以在这里找到: https://www.npmjs.com/package/ngx-dropzone-wrapper