nodejs处理图片文件上传

18 篇文章 1 订阅

如果使用express框架的话,其内置模块就可以直接处理文件上传了,而不需要饱含额外的模块。

express版本:3.4.4

1,使用bodyParser过滤器,并且指定上传的目录为public/upload,注意这里的目录为相对于express框架app运行的路径,或者指定绝对路径。

app.use(express.bodyParser({ uploadDir: "./public/upload" }));
2,编写处理上传文件的nodejs代码,存在routes/upload.js中:

//处理图像文件上传,图像文件保存在public/upload下
exports.upload = function (req, res) {
    console.log(req.files);
    var patharray = req.files.file.path.split("\\");
    res.send(patharray[patharray.length-1]);
}

进入upload函数时express已经把文件上传都处理好了,并且保存在public/upload下了,文件名为req.files.file.path,这里面的”file“为前台页面文件input的id名称,所以这里只是简单地将文件名返回,这个文件名是express重新命名过了,保证唯一,并不是你上传时的文件名。

3,设置路由

var upload = require('./routes/upload');
app.post('/upload', upload.upload);

4,前台编写上传处理代码

页面代码:

<div class="ps-image" style="background-image:url('<%- product_list[i].pic %>'); "><input type="file" id="file" οnchange="onselectimage()" style="filter:alpha(opacity=0);opacity:0;width:100%;height:100%;"/>
</div>
采用ajax+formdata上传文件,所以这里form节点都不需要,所有处理都在onselectimage里面:

//选择文件之后直接上传
function onselectimage() {
    var xmlHttpReq = null;
    //IE浏览器使用ActiveX
    if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //其它浏览器使用window的子对象XMLHttpRequest
    else if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    var filenode = document.getElementById("file");


    if (xmlHttpReq != null) {
        //设置回调,当请求的状态发生变化时,就会被调用
        xmlHttpReq.onreadystatechange = function () {
            //等待上传结果
            if (xmlHttpReq.readyState == 1) {
                filenode.parentNode.style.backgroundImage = "url('/images/bigloader.gif')";
            }
            //上传成功,返回的文件名,设置到div的背景中
            if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
                filenode.parentNode.style.backgroundImage = "url('/upload/" + xmlHttpReq.responseText + "')";
            }
        }
        //构造form数据
        var form = new FormData();
        form.append("file", filenode.files[0]);


        //设置请求(没有真正打开),true:表示异步
        xmlHttpReq.open("POST", "/upload", true);
        //不要缓存
        //xmlHttpReq.setRequestHeader("If-Modified-Since", "0");
        //提交请求
        xmlHttpReq.send(form);
        //清除掉,否则下一次选择同样的文件就进入不到onchange函数中了
        filenode.value = null;
    }
}

参考资料:

1,Upload progress bar working with apache, nginx and lighttpd upload progress modules

2,模拟AJAX无刷新的文件上传功能

3,关于真正的Ajax方式上传文件

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值