Express 文件上传

首先需要创建一个express工程:express /temp/upload&& cd /temp/upload
然后安装组件: npm install -d

打开index.jade文件构建一个输出给用户的页面:
html
 head
     meta(http-equiv='Content-Type', content='text/html',charset='UTF-8')

 body
    form(action='/showImage/imageFile',enctype='multipart/form-data' ,method='post')
           input(type='text',name='username',id='fileInformation')
           input( type='file', name='upload',id='imageFile',multiple='multiple')
           input( type='submit', value='上传')

在app.js中配置路由并且设置如何处理post上来的数据:
app.get('/showImage',routes.showImage);

//使用标准的redirect after post 模式
app.post('/showImage/:id', function (req, res) {
    var id = req.params.id;
    console.log("the id is:"+id);
//    console.log(req.files.upload);
    var tmp_path = req.files.upload.path;
    fs.renameSync(tmp_path,"/tmp/test.png");//采用同步的方式把图片放到缓存
    if(id=="imageFile")
    {
        console.log(" the image is exist!");
        res.redirect('http://localhost:3000/showImage');
    }
    else{
        res.send("the request is not exist!");
        res.end();
    }

});
然后在index.js中添加一个接口模块:
exports.showImage = function(req, res){
//    res.render('showImage');
    fs.readFile("/tmp/test.png", "binary", function(err, file) {//读取缓存
        res.writeHead(200, {"Content-Type": "image/png"});
        res.write(file, "binary");//采用二进制的方式输出到页面
//        fs.unlink("/tmp/test.png");
        res.end();
    });
};


//使用先把文件存储再显示的模式(需要自己写一个file-upload页面jade文件,注意改一下inde.jade中form表单的action改为'/file-upload')
app.post('/file-upload', function(req, res, next) {
    console.log(req.body);
    console.log(req.files);
    var tmp_path = req.files.upload.path; // 获得文件的临时路径
    var target_path = './public/images/' + req.files.upload.name;// 指定文件上传后的目录
    fs.rename(tmp_path, target_path, function(err) { // 移动文件
        if (err) throw err;
        fs.unlink(tmp_path, function() {// 删除临时文件夹文件,
                if (err) throw err;
                var uploadImageSize=req.files.upload.size;
                var uploadImageName=req.files.upload.name;
                res.render("file-upload",{imagePath:target_path,imageSize:uploadImageSize,imageName:uploadImageName});
                res.end();
            }
        )
    });
});


file-upload.jade:
html
   head
        meta(http-equiv='Content-Type', content='text/html', charset='UTF-8')
   body
        p 上传文件目录:#{imagePath}
        p 上传文件大小:#{imageSize}bytes
        img(src='images/#{imageName}',alt='images')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值