Express file upload

1. In the project directory, the necessary components for installation by the install Multiparty NPM
NPM Multiparty --save the install-dev

2.app.js added
app.use (bodyParser ({uploadDir: ' ./ uploadtemp'})); // set the temporary folder upload
// Create uploadtemp file folder directory of the same app.js

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

// File Upload ------- ------
router.post ( '/ imgupload', function (REQ, RES) {
// --------------- --------------------------
var form = new new multiparty.Form ();
// set the edit
form.encoding = 'utf-8';
// set the file storage path
form.uploadDir = "./uploadtemp/";
// set single file size limit
form.maxFilesSize = 2 * 1024 * 1024;
//form.maxFields = 1000; thus the total size of the file set

form. the parse (REQ, function (ERR, Fields, Files) {

  for (var in Key Files) {
    the console.log (Key + '==' + Files [Key]);
    for (var KK in Files [Key] [0]. headers) {
    the console.log (KK + '===' + Files [Key] [0] .headers [KK]);
  }
}
file1 = Files [ 'myimg'];
ParaName = file1 [0] .fieldName;// parameter name myimg
originalFilename = file1 [0] .originalFilename; // original filename
tmppath = file1 [0] .path; // uploads \ mrecQCv2cGlZbj-UMjNyw_Bz.txt
fileSize = file1 [0] .size; // file size

var timestamp = new Date () .getTime (); // get the current timestamp
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);
  }
});// renamed to the real file name
* /


/ *
Fs.rename (tmppath, newPath, function (ERR) {
  IF (ERR) {
    the console.log ( 'the rename error:' + ERR);
  } {the else
    the console.log ( 'the rename OK');
  }
});
* /
// delete files in the temporary folder
//fs.unlinkSync(tmpPath);

});
// ------------------------- ----------------
  res.send ( 'uploaded');
});

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>

If the uploads folder is not a temporary installation again:
D: \ the 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.服务端:
was multi party = require ( 'multi-party');
was util = require ( 'util');
was fs = require ( 'FS');

// ----- image upload
router.post ( '/ uploadImg', function (REQ, RES) {
var form = new new multiparty.Form ();
// set the encoding
form.encoding = 'UTF-. 8';
/ / setting file storage path
form.uploadDir = "./uploadtemp/";
// set single file size limit
form.maxFilesSize = 2 * 1024 * 1024;
//form.maxFields = 1000; thus the total size of the file is provided

form.parse (REQ, function (ERR, Fields, Files) {
  uploadURL with = '/ Images / Upload /'
  file1 = Files [ 'Filedata'];
  ParaName = file1 [0] .fieldName; // parameter name Filedata
  OriginalFilename = file1 [0] .originalFilename; // original filename
  tmppath = file1 [0] .path; // uploads \ mrecQCv2cGlZbj-UMjNyw_Bz.txt
  fileSize = file1 [0] .size; // file size

  var timestamp = new Date () getTime (). ; // get the current timestamp
  uploadurl += timestamp+originalFilename
  newPath= './public'+uploadurl;

  fs.createReadStream fileReadStream = var (tmppath);
  var = fileWriteStream fs.createWriteStream (newPath);
  fileReadStream.pipe (fileWriteStream); // pipe flow
  fileWriteStream.on ( 'Close', function () {
    fs.unlinkSync (tmppath); // delete the temporary folder image
    the console.log ( 'over Copy');
    res.send ( '{ "ERR": "", "MSG": "' + uploadURL with + '"}')
  });
}) ;
// -----------------------------------------
//res.send ( 'Upload');
});

Guess you like

Origin www.cnblogs.com/xintao/p/11652719.html