nodejs 实现模拟form表单上传文件


Posted in NodeJs onJuly 14, 2014

以前项目里有这个方法,最近在客户那里出问题了,同事说,这个方法从来就没管用过,SO,用了一天时间把这个方法给搞出来了(觉得花费的时间长了点),分享之。

代码及测试用例:

var http = require('http');
var path = require('path');
var fs = require('fs');

function postFile(fileKeyValue, req) {
  var boundaryKey = Math.random().toString(16);
  var enddata = '\r\n----' + boundaryKey + '--';

  var files = new Array();
  for (var i = 0; i < fileKeyValue.length; i++) {
   var content = "\r\n----" + boundaryKey + "\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Disposition: form-data; name=\"" + fileKeyValue[i].urlKey + "\"; filename=\"" + path.basename(fileKeyValue[i].urlValue) + "\"\r\n" + "Content-Transfer-Encoding: binary\r\n\r\n";
   var contentBinary = new Buffer(content, 'utf-8');//当编码为ascii时,中文会乱码。
   files.push({contentBinary: contentBinary, filePath: fileKeyValue[i].urlValue});
  }
  var contentLength = 0;
  for (var i = 0; i < files.length; i++) {
   var stat = fs.statSync(files[i].filePath);
   contentLength += files[i].contentBinary.length;
   contentLength += stat.size;
  }

  req.setHeader('Content-Type', 'multipart/form-data; boundary=--' + boundaryKey);
  req.setHeader('Content-Length', contentLength + Buffer.byteLength(enddata));

  // 将参数发出
  var fileindex = 0;
  var doOneFile = function(){
   req.write(files[fileindex].contentBinary);
   var fileStream = fs.createReadStream(files[fileindex].filePath, {bufferSize : 4 * 1024});
   fileStream.pipe(req, {end: false});
   fileStream.on('end', function() {
     fileindex++;
     if(fileindex == files.length){
      req.end(enddata);
     } else {
      doOneFile();
     }
   });
  };
  if(fileindex == files.length){
    req.end(enddata);
  } else {
    doOneFile();
  }      
}

//测试用例
//http://nodejs.org/api/http.html#http_http_request_options_callback
var files = [
 {urlKey: "file1", urlValue: "E:\\DFBF.jpg"},
 {urlKey: "file2", urlValue: "E:\\1.jpg"},
 {urlKey: "file3", urlValue: "E:\\Pro 空格 中文.mp3"}
]
var options = { 
 host: "localhost", 
 port: "8908" , 
 method: "POST", 
 path: "/Home/Upload"
}

var req = http.request(options, function(res){
 console.log("RES:" + res);
 console.log('STATUS: ' + res.statusCode);
 console.log('HEADERS: ' + JSON.stringify(res.headers));
 //res.setEncoding("utf8");
 res.on("data", function(chunk){
  console.log("BODY:" + chunk);
 })
})

req.on('error', function(e){
 console.log('problem with request:' + e.message);
 console.log(e);
})
postFile(files, req);
console.log("done");

服务端测试,用mvc在home控制器写了个upload方法,并遍历上传的文件将其保存在硬盘上了。

只是上传大文件会有问题,估计是需要服务器进行配置,暂且不管。

服务端方法(写在了Home控制器下)

[HttpPost]
    public string Upload()
    {
      //HttpPostedFileBase file = this.Request.Files["file"];

      //file.SaveAs(file.FileName);

      foreach (string file in this.Request.Files)
      {
        this.Request.Files[file].SaveAs(@"E:\新建文件夹\" + this.Request.Files[file].FileName);
      }

      return @"保存成功 路径:E:\新建文件夹\";
    }

运行脚本:

node nodejsPostFile.js

运行结果:

nodejs 实现模拟form表单上传文件

NodeJs 相关文章推荐
nodejs 后缀名判断限制代码
Mar 31 NodeJs
Nodejs极简入门教程(一):模块机制
Oct 25 NodeJs
基于Nodejs利用socket.io实现多人聊天室
Feb 22 NodeJs
详谈Angular路由与Nodejs路由的区别
Mar 05 NodeJs
详解nodejs爬虫程序解决gbk等中文编码问题
Apr 06 NodeJs
解析NodeJS异步I/O的实现
Apr 13 NodeJs
Windows下快速搭建NodeJS本地服务器的步骤
Aug 09 NodeJs
nodejs中art-template模板语法的引入及冲突解决方案
Nov 07 NodeJs
详解IWinter 一个路由转控制器的 Nodejs 库
Nov 15 NodeJs
Nodejs连接mysql并实现增、删、改、查操作的方法详解
Jan 04 NodeJs
浅谈使用nodejs搭建web服务器的过程
Jul 20 NodeJs
nodejs+express最简易的连接数据库的方法
Dec 23 NodeJs
14款NodeJS Web框架推荐
Jul 11 #NodeJs
基于promise.js实现nodejs的promises库
Jul 06 #NodeJs
我的NodeJs学习小结(一)
Jul 06 #NodeJs
nodejs中使用monk访问mongodb
Jul 06 #NodeJs
nodejs之请求路由概述
Jul 05 #NodeJs
Nodejs中自定义事件实例
Jun 20 #NodeJs
Nodejs sublime text 3安装与配置
Jun 19 #NodeJs
You might like
《五等分的花嫁》漫画完结!2020年10月第2期TV动画制作组换血!
2020/03/06 日漫
php+jquery编码方面的一些心得(utf-8 gb2312)
2010/10/12 PHP
PHP实现二维数组去重功能示例
2017/01/12 PHP
js里取容器大小、定位、距离等属性搜集整理
2013/08/19 Javascript
js解决select下拉选不中问题
2014/10/14 Javascript
jQuery实现自动调整字体大小的方法
2015/06/15 Javascript
通过正则表达式获取url中参数的简单实现
2016/06/07 Javascript
AngularJS 避繁就简的路由
2016/07/01 Javascript
bootstrap table操作技巧分享
2017/02/15 Javascript
js实现登录框鼠标拖拽效果
2017/03/09 Javascript
Angular2学习笔记之数据绑定的示例代码
2018/01/03 Javascript
详解用Webpack与Babel配置ES6开发环境
2019/03/12 Javascript
keep-alive不能缓存多层级路由菜单问题解决
2020/03/10 Javascript
React实现轮播效果
2020/08/25 Javascript
python编写分类决策树的代码
2017/12/21 Python
python 获取当天凌晨零点的时间戳方法
2018/05/22 Python
详解在python操作数据库中游标的使用方法
2019/11/12 Python
Python获取统计自己的qq群成员信息的方法
2019/11/15 Python
python Tensor和Array对比分析
2020/01/08 Python
TensorFlow实现保存训练模型为pd文件并恢复
2020/02/06 Python
python批量替换文件名中的共同字符实例
2020/03/05 Python
Python自动发送和收取邮件的方法
2020/08/12 Python
CSS伪类与CSS伪元素的区别及由来具体说明
2012/12/07 HTML / CSS
印度婴儿用品在线商店:Firstcry.com
2016/12/05 全球购物
GLAMGLOW香港官网:明星出镜前的秘密武器
2017/03/16 全球购物
英国工具中心:UK Tool Centre
2017/07/10 全球购物
如何用SQL语句进行模糊查找
2015/09/25 面试题
求职信范文英文版
2014/01/05 职场文书
竞聘上岗演讲稿范文
2014/01/10 职场文书
捐书寄语赠言
2014/01/18 职场文书
综合办公室岗位职责
2015/04/11 职场文书
入党函调证明材料
2015/06/19 职场文书
聊聊golang中多个defer的执行顺序
2021/05/08 Golang
InterProcessMutex实现zookeeper分布式锁原理
2022/03/21 Java/Android
bose降噪耳机音能消除人声吗
2022/04/19 数码科技
MySQL数据库实验之 触发器和存储过程
2022/06/21 MySQL