我想使用Angular,Node.js和Mongoose(GridFS)上传并保存单个或多个图像。 另一种保存图像的方法是Base64,但我想使用GridF。
使用Angular 7。
在后端,我只看到req.file
未定义而req.body
为{}为空。
我将文件数据附加到formData
中,并通过Angular将其传递到HTTP请求中。在console.log(this.files)
上,我可以在浏览器控制台中查看数据。我也已经对Postman进行了测试。
HTML
<mat-step [stepControl]="photoForm">
<form [formGroup]="photoForm">
<ng-template matStepLabel>Photos</ng-template>
<div class="container">
<div class="imagePreview" *ngFor="let x of imageSrc" (click)="deleteImage($event)">
<img class="img" [src]="x" />
</div>
</div>
<input type="file" multiple (change)="onFileChange($event)" #fileInput style="display: none" />
<button (click)="fileInput.click()">Select File</button>
</form>
</mat-step>
Angular
onFileChange(event) {
if (event.target.files && event.target.files.length) {
this.files = event.target.files;
}
onSubmit() {
const uploadData = new FormData();
uploadData.append('myFile', this.files, this.files.name);
this.http.post(url + '/api/upload', uploadData).subscribe((item) => {
console.log(item);
});
}
Node.js
import * as compression from "compression";
import * as express from "express";
import * as bodyParser from "body-parser";
import * as mongoose from "mongoose";
import { Routes } from "./routes/routes";
import * as cors from 'cors';
import { urlencoded } from "body-parser";
import { Contact } from "./routes/contact";
import { AddTour } from "./routes/addTour";
const path = require('path');
const mongoURI = 'mongodb://127.0.0.1/testDB';
let gfs;
//GridFS
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
class App {
public app: express.Application;
public addTourObj: AddImages = new AddImages();
constructor() {
this.app = express();
this.config();
this.addTourObj.addImage(this.app);
this.connectMongoDB();
/** Setting up storage using multer-gridfs-storage */
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
var upload = multer({ //multer settings for single upload
storage: storage
}).single('file');
}
private config() {
this.app.use(cors());
this.app.options('*', cors());
this.app.use(bodyParser.json());
this.app.use(urlencoded({ extended: true }));
this.app.use(compression());
}
private connectMongoDB() {
const conn = mongoose.createConnection(mongoURI);
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
}
}
export default new App().app;
Node.js AddImage.ts
import { Request, Response } from "express";
import { request } from "http";
export class AddImage {
public addImage(app): void {
app.route('/api/upload').post((req, res) => {
console.log(req.file) // is undefined
console.log(req.body) // is empty {}
});
}
}
结果应该使用Gridfs将图像上传到MongoDB中,我需要再次检索或删除它。
我可以在浏览器中将formData视为file:二进制文件。
答案 0 :(得分:0)
替换此uploadData.append('myFile', this.files, this.files.name);
与uploadData.append('file', this.files, this.files.name);