express4.0以上版本檔案上傳

來源:互聯網
上載者:User

標籤:http   io   os   ar   java   for   sp   檔案   資料   

發現很多node的書介紹express檔案上傳都是基於3.*版本的,

現在express的版本都是4.+的,很多以前的代碼跑不動了

所以自己折騰了個小demo

實現了限制上傳檔案種類和大小

例子是基於formidable模組的

github地址為https://github.com/felixge/node-formidable

var express = require('express');var formidable = require('formidable');var router = express.Router();var fs =require('fs');/* GET home page. */router.get('/', function(req, res) {  res.render('index', { title: 'Express' });});router.post('/', function(req, res) {  //設定返回字串編碼  res.header( 'Content-Type','text/javascript;charset=utf-8');  //new一個formidable.IncomingForm();  var form = new formidable.IncomingForm();  //設定臨時檔案存放的路徑  form.uploadDir = "./routes";  //設定上傳資料的編碼  form.encoding='utf-8';  //設定是否保持上傳檔案的拓展名  form.keepExtensions = true;  //檔案上傳過程中觸發可以做上傳進度查看  form.on('progress', function(bytesReceived, bytesExpected) {    if(bytesExpected>1024*1024*3){//bytesExpected為等待上傳的檔案的大小,超過大小就返回錯手動觸發error      this.emit('error',"檔案過大")    };  });  //返回非檔案的部分資料  form.on('field', function(name, value) {    console.log(name+" "+value)  });  //檔案上傳成功後觸發  form.on('file', function(name, file) {    if(file.type!='text/css'){//檔案類型不是合法的      this.emit('error',"不允許的類型");//手動觸發error      fs.unlink(file.path)//刪掉臨時檔案    }    else {      //成功上傳,把臨時檔案移動到public檔案夾下面      fs.renameSync(file.path, "./public/" + file.name);    }  });  //流程正常處理  form.on('end',function(){    res.end('上傳成功');  });  //出錯  form.on('error',function(err){    res.end(err);  })  //執行檔案上傳任務  form.parse(req,function(){  });});module.exports = router;
demo http://download.csdn.net/detail/a5799694/8109927


express4.0以上版本檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.