nodejs处理图片文件上传

如果使用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" onchange="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方式上传文件

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...