Nodejs學(xué)習(xí)筆記(六)

Node.js Upload Files

1.上傳文件需要用到Formidable Module,該Module通過npm install formidable來下載

2.安裝完成候引入:var formidable = require('formidable');

3.new一個(gè)IncomingForm對象: var form = new formidable.IncomingForm();

4.解析上傳的文件:

    form.parse(req, function (err, fields, files) {
        res.write('File uploaded and moved!');
        res.end();

5.通過fs Module來重命名上傳的文件:

    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = '/tmp/upload/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });

最后所有的完整代碼如下:

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

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = '/tmp/upload/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 個(gè)人入門學(xué)習(xí)用筆記、不過多作為參考依據(jù)。如有錯(cuò)誤歡迎斧正 目錄 簡書好像不支持錨點(diǎn)、復(fù)制搜索(反正也是寫給我自己看...
    kirito_song閱讀 2,649評論 1 37
  • 安裝 Mysql安裝http://ftp.ntu.edu.tw/MySQL/Downloads/MySQLInst...
    秋天de童話閱讀 1,421評論 0 8
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,603評論 0 6
  • Node.js 常用工具 util 是一個(gè)Node.js 核心模塊,提供常用函數(shù)的集合,用于彌補(bǔ)核心JavaScr...
    FTOLsXD閱讀 606評論 0 2
  • Node基本 node的最大特性莫過于基于事件驅(qū)動(dòng)的非阻塞I/O模型。 node通過事件驅(qū)動(dòng)的方式處理請求,無須為...
    AkaTBS閱讀 2,305評論 0 11

友情鏈接更多精彩內(nèi)容