nodejs处理图片文件上传
来源:互联网 发布:男款汉服款式知乎 编辑:程序博客网 时间:2024/05/01 19:14
如果使用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方式上传文件
- nodejs处理图片文件上传
- nodejs(express)处理图片上传
- nodejs express 文件上传处理
- 如何使用nodejs上传图片/文件
- nodejs文件上传处理模块formidable
- [上传]文件上传以及图片处理(转)
- 用NODEJS处理EXCEL文件导入导出,文件上传
- nodejs上传图片
- nodejs实现图片上传
- nodejs图片上传显示
- nodejs小记之formidable同步图片文件上传
- nodejs 处理表单上传文件时,获取不到表单数据
- nodejs express 上传文件
- NODEJS 上传文件
- nodejs 安装 上传文件
- Nodejs 文件上传
- nodeJs 接收上传文件
- nodejs 上传文件
- android图像处理系列之三--图片色调饱和度、色相、亮度处理
- 正被停用的激活上下文不是最近激活的
- (Relax 1.2)POJ 1528 Perfection(求一个数各个因子之和)
- WinCE6过试用期 Error: failed PB timebomb check
- php操作mysql两个数据库中表的数据同步
- nodejs处理图片文件上传
- 在MyEclipse下修改tomcat默认的运行方式
- 请教电源切换电路,直流输入和锂电池之间切换如何设计最好。另请推荐2节锂电池的充电
- FILE I/O
- Microsoft Office Excel 不能访问文件
- Java集合框架比较
- FlexBuilder4.6创建手机项目之调用手机摄像头
- android图片特效处理之图片叠加
- 第十二周-当年第几天