欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NodeJS,通过Express + multer 接受上传文件

程序员文章站 2022-06-02 20:14:01
...

SERVER code:
“use strict”
const ExpressLib = require(“express”);
const Multer = require(“multer”);
const Fs = require(“fs”);
const ObjMulter = Multer({dest: ‘./dmp_files’});
const ServerConfig = require("…/gameConfig/serverConfig");

class HttpWebServer {
constructor() {
this.startHttpServer();
}
startHttpServer() {
// 基于express框架的node服务器
let server = ExpressLib();

    // 允许所有类型的文件传递过来
    server.use(ObjMulter.any())

    //upload files
    server.post('/uploadfile', (req, res) => {
        console.log(req.files[0])
        //var newName = req.files[0].path+pathLib.parse(req.files[0].originalname).ext
        var newName = req.files[0].destination + "/" + req.files[0].originalname;
        console.log(newName);
        // 利用fs模块的文件重命名
        // req.files[0].path这个是文件的在传递中被修改的名字,newName是文件原名称,function回调函数
        Fs.rename(req.files[0].path, newName, function(err){
            if(err){
                res.send('dmp upload failure!');
            }else{
                res.send('dmp upload success!');
            }
        })
    });


    server.listen(8092, () => {
        Logger.info(`[-listening on port ${8092}-]`);
    });
}

};
module.exports = HttpWebServer ;

Client:

Files:

END

相关标签: Like