Express文件上传

1.在项目目录中,通过npm install multiparty进行安装必要组件
npm install multiparty --save-dev

2.app.js中添加
app.use(bodyParser({uploadDir:'./uploadtemp'}));//设置上传临时文件夹
//在与app.js同目录下创建uploadtemp文件夹

3.index.js中
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');

//-------文件上传------
router.post('/imgupload',function(req,res){
//-----------------------------------------
var form = new multiparty.Form();
//设置编辑
form.encoding = 'utf-8';
//设置文件存储路径
form.uploadDir = "./uploadtemp/";
//设置单文件大小限制
form.maxFilesSize = 2 * 1024 * 1024;
//form.maxFields = 1000; 设置所以文件的大小总和

form.parse(req, function(err, fields, files) {

  for(var key in files){
    console.log(key+'=='+files[key]);
    for(var kk in files[key][0].headers){
    console.log(kk+'==='+files[key][0].headers[kk]);
  }
}
file1 = files['myimg'];
paraname = file1[0].fieldName; //参数名myimg
originalFilename = file1[0].originalFilename; //原始文件名
tmpPath = file1[0].path;//uploads\mrecQCv2cGlZbj-UMjNyw_Bz.txt
fileSize = file1[0].size; //文件大小

var timestamp=new Date().getTime(); //获取当前时间戳
newPath= './public/images/'+timestamp+originalFilename;

var fileReadStream = fs.createReadStream(tmpPath);
var fileWriteStream = fs.createWriteStream(newPath);
fileReadStream.pipe(fileWriteStream); //管道流
fileWriteStream.on('close',function(){
  console.log('copy over');
});
/*
function writeFile(data){
  fs.writeFile(newPath,data,function(error){
    if(error){
      throw error;
    }else{
      console.log("文件已保存");
    }
  });
}
fs.readFile(tmpPath,'ascii',function(err, data) {
  if (err) {
    console.log("读取失败");
  } else {
    writeFile(data);
  }
});
*/

//重命名为真实文件名
/*
fs.rename(tmpPath, newPath, function(err) {
  if(err){
    console.log('rename error: ' + err);
  } else {
    console.log('rename ok');
  }
});
*/
//删除临时文件夹中的文件
//fs.unlinkSync(tmpPath);

});
//-----------------------------------------
  res.send('上传完成');
});

4.客户端
<html>
<head>
  <link rel="stylesheet" href='/flex.css'/>
</head>
<body>
  <% include header %>
  <form enctype="multipart/form-data" method='post' action='/imgupload'>
  <table border='1' align='center'>
    <tr>
      <td>图片上传</td>
    </tr>
    <tr>
      <td>
        <input type='file' name='myimg'/>
      </td>
    </tr>
    <tr>
      <td align='center'>
        <input type='submit' value='上传'/>
      </td>
    </tr>
  </table>
  </form>
  <% include footer%>
</body>
</html>

如果uploads不是临时文件夹再次安装:
D:\www\nodejs2\blog>npm install body-parser --save-dev

<!----------------xheditor下ajax上传图片---------->
1.客户端:
<script type="text/javascript" src="/xheditor-1.2.2.min.js"></script>
<script type="text/javascript" src="/xheditor_lang/zh-cn.js"></script>
<script type="text/javascript">
$(pageInit);
function pageInit()
{
  $.extend(XHEDITOR.settings,{shortcuts:{'ctrl+enter':submitForm}});
        $('#content').xheditor({html5Upload:false,upMultiple:'1',upLinkUrl:"/uploadFile",upLinkExt:"zip,rar,txt",upImgUrl:"/uploadImg",upImgExt:"jpg,jpeg,gif,png",upFlashUrl:"/uploadFlash",upFlashExt:"swf",upMediaUrl:"/uploadMedia",upMediaExt:"wmv,avi,wma,mp3,mid"});
}
function insertUpload(arrMsg)
{  console.log(arrMsg)
  var i,msg;
  for(i=0;i<arrMsg.length;i++)
  {
    msg=arrMsg[i];
    $("#uploadList").append('<option value="'+msg.id+'">'+msg.localname+'</option>');
  }
}
function submitForm(){$('#frmDemo').submit();}
</script>

<textarea id="content" name="content" cols="120" rows="9"></textarea>

2.服务端:
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');

//-----图片上传
router.post('/uploadImg',function(req,res){
var form = new multiparty.Form();
//设置编码
form.encoding = 'utf-8';
//设置文件存储路径
form.uploadDir = "./uploadtemp/";
//设置单文件大小限制
form.maxFilesSize = 2 * 1024 * 1024;
//form.maxFields = 1000; 设置所以文件的大小总和

form.parse(req, function(err, fields, files) {
  uploadurl='/images/upload/'
  file1 = files['filedata'];
  paraname = file1[0].fieldName; //参数名filedata
  originalFilename = file1[0].originalFilename; //原始文件名
  tmpPath = file1[0].path;//uploads\mrecQCv2cGlZbj-UMjNyw_Bz.txt
  fileSize = file1[0].size; //文件大小

  var timestamp=new Date().getTime(); //获取当前时间戳
  uploadurl += timestamp+originalFilename
  newPath= './public'+uploadurl;

  var fileReadStream = fs.createReadStream(tmpPath);
  var fileWriteStream = fs.createWriteStream(newPath);
  fileReadStream.pipe(fileWriteStream); //管道流
  fileWriteStream.on('close',function(){
    fs.unlinkSync(tmpPath); //删除临时文件夹中的图片
    console.log('copy over');
    res.send('{"err":"","msg":"'+uploadurl+'"}')
  });
});
//-----------------------------------------
//res.send('上传');
});

posted on 2019-10-11 10:45  _xinT  阅读(1084)  评论(0编辑  收藏  举报