美文网首页开发Node.jsNode
node.js+express 文件上传以及图片上传

node.js+express 文件上传以及图片上传

作者: hey_前端豆 | 来源:发表于2016-07-26 16:36 被阅读2268次

文件上传
multer模块官网

  • html页面
<form method="post" enctype="multipart/form-data" class="uploadFile" action="lalocal-sales/customers/excel">
       <button class="btn btn-success btn-file-up"><input type="file" name="file" class="file_up" id='file'>上传文件</button>
 </form>
  • js代码
$('.file_up').change(function() {
    $('.uploadFile').submit();
});
  • node层
    先引入multer模块,设置文件上传目录
var multer = require('multer');
var upload = multer({
    dest: './upload/'
});

再对上传的文件进行格式化

router.post("/customers/excel",upload.single('file'),function(req,res,next) {
    var url = global.baseURL+req.url;
  console.log('url................................'+url);
  console.log('请求路径.....'+req.url);
    var obj = req.file;
    var tmp_path = obj.path;
    var new_path = "upload/excelfile.XLSX";
    console.log("原路径:" + tmp_path);
    /*修改上传文件地址*/
    fs.rename(tmp_path, new_path, function(err) {
            if (err) {
                    throw err;
            }
    });

最后上传到服务器

superagent
                 .post(url)
        .attach('file', new_path)
        .end(function(err1, res1) {
        if (res1.ok) {
                    console.log(JSON.stringify(res1.body));
                    fs.unlinkSync(new_path);//删除 
                    res.redirect(global.rootUrl+'custom');
                    }
            });

相关文章

网友评论

    本文标题:node.js+express 文件上传以及图片上传

    本文链接:https://www.haomeiwen.com/subject/hzwnjttx.html