Angular和Nodejs:发送图片

时间:2018-04-24 05:18:20

标签: node.js angular

对于我的angular + nodejs应用,我有以下内容上传图片:

file.ts

 handleFileInput(files: FileList) {
    var filename = files.item(0);
    this.upload(filename).subscribe();
};


upload(fileToUpload: File){   
  console.log(fileToUpload); //Here I can see all the image data     

  let obj = {
        imageData: fileToUpload,
        imageID: "Sample"
  };

  return this.http.post<any>(url, obj ,{});
}

然后在nodejs中,uploadController.js

private initAPI(): void {
    this.router.route('/file')
        .post((req, res) => {
            console.log(req);   //No "body" data             
       });
}

当我获得数据时,我可以看到以下内容:

body:
   imageData: Object {}
   imageID: "Sample"

imageData为空。有关如何发送图像的任何建议吗?

感谢。

2 个答案:

答案 0 :(得分:2)

这可以使用角度侧的formData来完成,并使用节点侧的multer来上传文件。

  

角度部分

component.html

<div>
  <div>
    <input type="file" (change)="createFormData($event)">
  </div>
  <button (click)="upload()">Upload</button>
</div>

componenet.ts

  selectedFile: File = null;
  fd = new FormData();

  constructor(private http: HttpClient) {}

  createFormData(event) {
    this.selectedFile = <File>event.target.files[0];
    this.fd.append('file', this.selectedFile, this.selectedFile.name);
  }

  upload() {
    this.http.post(url, this.fd)
    .subscribe( result => {
      console.log(result)
    });
  }
  

节点部分

const express = require('express');
const router = express.Router();
var multer = require("multer");
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './upload')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
const upload = multer({
    storage: storage
})

router.post('url',  upload.single('file'), (req, res) => {
  // the file is uploaded when this route is called with formdata.
  // now you can store the file name in the db if you want for further reference.
  const filename = req.file.filename;
  const path = req.file. path;
  // Call your database method here with filename and path
  res.json({'message': 'File uploaded'});
});

module.exports = router;

答案 1 :(得分:0)

安装ng2-file-upload
npm i ng2-file-upload --save

component.html

<label class="image-upload-container btn btn-bwm">
  <span>Select New Image</span>
  <div *ngIf="selectedFile">
    <img src="{{selectedFile.src}}" class="img_profile img-circle" >
   </div>
  <input #imageInput
         type="file"
         accept="image/*" ng2FileSelect [uploader]="uploader"
         (change)="processFile(imageInput)" name="newImage">
</label>

app.module.ts

import { FileSelectDirective } from 'ng2-file-upload';

//in declaration
declarations: [ ...,
FileSelectDirective,
... ],

component.ts

 import { Component, OnInit,ViewContainerRef,ElementRef,ViewChild } from '@angular/core';
import {  FileUploader } from 'ng2-file-upload/ng2-file-upload';
//Set api url
const URL = 'http://127.0.0.1:3000/users/uploadFile';


//Apply for preview. add before export class
class ImageSnippet {
pending: boolean = false;
  status: string = 'init';
 constructor(public src: string, public file: File) {}
}


 @Component({
  selector: 'app-imageupload',
  templateUrl: './imageupload.component.html',
  styleUrls: ['./imageupload.component.css']
})
//export class
export class ImageuploadComponent implements OnInit {
  public name:any
  constructor() { }

    selectedFile: ImageSnippet;

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file)=> { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
      console.log("ImageUpload:uploaded:", item, status, response);
     };
  }
  processFile(imageInput: any) {
    const file: File = imageInput.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', (event: any) => {

      this.selectedFile = new ImageSnippet(event.target.result, file);
      console.log(this.selectedFile.file);
    })
    reader.readAsDataURL(file);

   this.uploader.uploadAll();

}
 public uploader:FileUploader = new FileUploader({url: URL, itemAlias: 'newImage'});


}

节点部分

var express = require('express');
var app = express();
var multer = require('multer');
var path = require('path');


//Apply Path to diskStorage and File Name with extension
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, '../src/assets/uploads/')
    },
    filename : function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
  });
   //Store in storage
    const upload = multer({
        storage: storage
    });
//For Single File upload
const singleUpload = upload.single('newImage');

var imageName='';
//upload file api to upload file
app.post('/uploadFile',function(req,res){

    singleUpload(req, res, function(err) {

        if (err) {
            return res.status(422).send({errors: [{title: 'File Upload Error', detail: err.message}] });
        }else{
            imageName =  req.file.filename;
            console.log(req.file.path);
            var imagePath = req.file.path;
            return res.send({success:true,  imageName});
        }
    })
});

 module.exports = app