将发布请求中的图像文件保存在Node.JS中

时间:2018-08-09 13:32:35

标签: node.js mongodb typescript

我正在尝试从Angular 6应用发送图像(也尝试过POSTMan应用的图像发布,结果相同)。我的问题不是发送部分,而是获取它并将其保存在我的node.js服务器中。此代码适用于JSON数据,但我无法弄清楚如何使其适用于图像。我认为我需要更改controller.ts和/或app.ts中的逻辑-需要建议。 我有以下文件:


controller.ts

public addNewImage (req: Request, res: Response) {                
        let newImage = new Image(req.body);
        console.log("Insert Image request received!"); 
        newImage.save((err, image) => {
            if(err){
                res.send(err);
            }    
            res.send("Success!");        
        });
    }

model.ts

import * as mongoose from 'mongoose';

const Schema = mongoose.Schema;

export const ImageSchema = new Schema({
    image: {
    data: Buffer,
    contentType: String
}

});

routes.ts

app.route('/image')
        .post(this.imageController.addNewImage)
        .get(this.imageController.getImages)

app.ts

import * as express from "express";
import * as bodyParser from "body-parser";
import * as mongoose from "mongoose";
import * as cors from "cors";

import { Routes } from "./routes/crmRoutes";

class App {

    public app: express.Application;
    public routePrv: Routes = new Routes();
    public mongoUrl: string = 'mongodb://localhost/Testdb';  

    constructor() {
        this.app = express();
        this.config(); 
        this.routePrv.routes(this.app);    
        this.mongoSetup();    
    }

    private config(): void{

        this.app.use(bodyParser.json());
        this.app.use(bodyParser.raw());
        this.app.use(bodyParser.urlencoded({ extended: false }));      
        this.app.use(cors()); 
    }

    private mongoSetup(): void{
        mongoose.Promise = global.Promise;
        mongoose.connect(this.mongoUrl);    
    }

}

export default new App().app;

0 个答案:

没有答案