Angular和Nodejs: 发送图片
Angular和Nodejs: 发送图片
对于我的angular + nodejs应用程序,我有以下内容来上传图像:\nfile.ts\n
handleFileInput(files: FileList) { var filename = files.item(0); this.upload(filename).subscribe(); }; upload(fileToUpload: File){ console.log(fileToUpload); //在这里我可以看到所有的图像数据 let obj = { imageData: fileToUpload, imageID: "Sample" }; return this.http.post(url, obj ,{}); }
\n然后在nodejs中,uploadController.js\n
private initAPI(): void { this.router.route('/file') .post((req, res) => { console.log(req); //没有“body”数据 }); }
\n当我获取数据时,我可以看到以下内容:\n
body: imageData: Object {} imageID: "Sample"
\nimageData
是空的。有没有关于如何发送图像的建议?\n谢谢。
Angular和Node.js:发送图片
问题的出现原因:在Angular中使用ng2-file-upload库来发送图片时,可能会遇到问题。
解决方法:按照以下步骤进行操作。
1. 首先安装ng2-file-upload库:
npm i ng2-file-upload --save
2. 在组件的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>
3. 在app.module.ts文件中添加以下代码:
import { FileSelectDirective } from 'ng2-file-upload'; //在declarations数组中添加FileSelectDirective declarations: [ ..., FileSelectDirective, ... ],
4. 在组件的ts文件中添加以下代码:
import { Component, OnInit,ViewContainerRef,ElementRef,ViewChild } from '/core'; import { FileUploader } from 'ng2-file-upload/ng2-file-upload'; //设置API的URL const URL = 'http://127.0.0.1:3000/users/uploadFile'; //用于预览图片的类 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 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'}); }
5. 在Node.js部分,添加以下代码:
var express = require('express'); var app = express(); var multer = require('multer'); var path = require('path'); //设置存储路径和文件名 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)) } }); const upload = multer({ storage: storage }); const singleUpload = upload.single('newImage'); var imageName=''; //上传文件的API 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
通过以上步骤,可以在Angular中使用ng2-file-upload库发送图片,并在Node.js中进行接收和处理。
问题:Angular和Nodejs之间如何发送图像文件?
原因:在Angular端使用formData并在Node端使用multer来上传文件。
解决方法:
1. 在Angular部分:
- 在HTML模板中,使用标签来选择图像文件,并在change事件中调用createFormData函数。
- 在component.ts文件中,定义selectedFile变量来保存选择的文件,使用FormData来创建一个表单数据对象,并将选择的文件添加到formData中。
- 在upload函数中,使用HttpClient的post方法将formData发送到指定的URL。
2. 在Node部分:
- 引入express、multer等模块,并创建一个路由对象。
- 使用multer的diskStorage方法定义存储路径和文件名的规则。
- 使用multer的upload方法创建一个上传中间件。
- 在路由中使用upload.single方法来处理上传的文件。
- 在路由处理函数中,可以对上传的文件进行处理,例如将文件名和路径保存到数据库中。
- 最后,返回一个JSON响应,表示文件上传成功。
完整代码如下:
Angular部分:
component.html
component.ts
import { HttpClient } from '@angular/common/http'; selectedFile: File = null; fd = new FormData(); constructor(private http: HttpClient) {} createFormData(event) { this.selectedFile =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); }); }
Node部分:
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) => { 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;
以上就是使用Angular和Nodejs发送图像文件的解决方法。