当先锋百科网

首页 1 2 3 4 5 6 7

上传单个文件的方法

1.在routes目录下添加upload.js文件(如果没有multer模块,则使用 npm install multer 来下载)

upload.js

var router = require('express').Router();
var multer = require('multer');
var gFilename = "";
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './tmp');   //此目录是项目根目录下的tmp目录,一定要确保此目录存在,否则上传失败
    },
    filename: function (req, file, callback) {
        gFilename = file.originalname;
        callback(null, gFilename);
    }
});
var upload = multer({storage: storage}).any();

router.post('/', function (req, res, next) {
    res.setTimeout(25000, function () {
        if (res.finished) {
            return;
        }
        var rtRes = {
            rstcode: "error",
            desc: "system timeout",
            data: {}
        };
        console.log("system response timeout");
        res.writeHead(501, {"Content-Type": "text/html"});
        res.write(JSON.stringify(rtRes));
        res.end();
    });

    upload(req, res, function (err) {
        if (res.finished) {
            return;
        }
        var rst = {
            rstcode: "error",
            desc: "上传失败",
            data: {filename: {}}
        };
        if (err) {
            return res.end(JSON.stringify(rst));
        }
        rst.rstcode = "success";
        rst.desc = "上传成功";
        rst.data.filename = gFilename;
        res.end(JSON.stringify(rst));
    });
});
module.exports = router;

2.在app.js文件中引入upload文件

var upload = require('./routes/upload');

app.use('/fileupload', upload);

3.测试表单

<form id="uploadForm" enctype="multipart/form-data" action="/fileupload" method="post">
    <input type="file" name="filename"/>
    <input type="submit" value="添加">
</form>
<!-- enctype="multipart/form-data"这句话的作用是将文件以二进制的形式上传,这样可以实现多种类型的文件上传 -->
具体可以查看node_modules目录下的multer模块中的README.md文件,有详细的介绍,这里告诉大家一个小技巧,nodejs的每个模块里边都有README.md文件,是对该模块的详细介绍,以及该模块如何使用(有小例子),非常方便