nodejs+ajax实现简单的文件上传功能
2016-04-10 16:07
1171 查看
app.js中引入express的第三方中间件multer实现文件上传功能。
路由
html
ajax
var multer = require('multer');//用express的第三方中间件 multer 实现文件上传功能。 app.use(multer({//设置文件上传到的位置 dest: './public/images/upload', rename: function (fieldname, filename) { return filename; } }));
路由
app.post('/upload', function (req, res) { req.flash('success', '文件上传成功!'); res.json({"result":{message:"文件上传成功!"}}); });
html
<input type="file" id="photo"> <button id="upload">上传</button>
ajax
/*上传文件*/ $("#upload").click(function(){ //do something var file = $("#photo")[0].files; //上次修改时间 console.log("文件上次修改时间"+file[0].lastModifiedDate); //名称 console.log("文件名称"+file[0].name); //大小 字节 console.log("文件大小"+file[0].size); //类型 console.log("文件类型"+file[0].type); //创建FormData对象 var data = new FormData(); //为FormData对象添加数据 $.each(file, function(i, file) { data.append('upload_file', file); }); $.ajax({ data: data, url: '/upload', type:"post", dataType: 'JSON', contentType: false, //不可缺 processData: false, //不可缺 success: function(data){ console.log(data); alert("上传成功!"); }, error: function(err){ console.log('error: ' + err); } }); })
相关文章推荐
- could only be replicated to 0 nodes, instead of 1
- hadoop 运行 datanode , mac 系统
- node入门(三)——gulp运用实例
- [译]How to Install Node.js on Ubuntu 14.04 如何在ubuntu14.04上安装node.js
- 文件的inode数据
- LeetCode 25 reverse-nodes-in-k-group
- node.js学习之路
- 基于NodeBB的网站服务器迁移步骤
- LeetCode *** 19. Remove Nth Node From End of List
- Hash_node_pseudo类
- inode
- LeetCode-237:Delete Node in a Linked List (Python)
- Yarn NodeManager restart特性
- node.js的几种异步控制的方法
- LeetCode117—Populating Next Right Pointers in Each Node II
- LeetCode116—Populating Next Right Pointers in Each Node
- leetcode 222. Count Complete Tree Nodes
- 点击链接更换图片和相应文本 childNotes nodeType nodeValue
- node入门(二)——gulpfile.js初探
- leetcode- Delete Node in a Linked List&Remove Linked List Elements