日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
使用HTTP上傳G級的文件之Node.js版本

不管喜歡與否,javascript無處不在。 我們可以在客戶端的前臺應用中找到它,也可以在大量的框架、類庫中找到它,而且可以在服務器端的后臺應用中找到它。

創(chuàng)新互聯(lián)服務項目包括路橋網(wǎng)站建設、路橋網(wǎng)站制作、路橋網(wǎng)頁制作以及路橋網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,路橋網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到路橋省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!

近年來, Javascript越來越流行,這似乎是由于 Javascript 生態(tài)系統(tǒng)正在幫助提高生產(chǎn)率、減少入門所需的時間。 在我的***篇文章中,我介紹了使用 ASP.NET Web 后端 API 實現(xiàn) G級文件上傳,發(fā)表完這篇文章后,我決定試一下使用 Node.js 能否達到同樣的效果。  這意味著我需要實現(xiàn) UploadChunk和 MergeAll方法,在 Node.js中我發(fā)表的 ***一篇文章談到了這一點。

開發(fā)環(huán)境

我們將使用 Visual Studio Express 2013 for Web 作為開發(fā)環(huán)境, 不過它還不能被用來做 Node.js 開發(fā)。為此我們需要安裝 Node.js Tools for Visual Studio。  裝好后 Visual Studio Express 2013 for Web 就會轉(zhuǎn)變成一個 Node.js IDE 環(huán)境,提供創(chuàng)建這個應用所需要的所有東西.。而基于這里提供的指導,我們需要:

下載安裝 Node.js  Windows 版,選擇適用你系統(tǒng)平臺的版本, Node.js (x86) 或者 Node.js (x64)。

下載并安裝 Node.js 的 Visual Studio 工具。

安裝完成后我們就會運行 Visual Studio Express 2013 for Web, 并使用 Node.js 的交互窗口來驗證安裝. Node.js 的交互窗口可以再 View->Other Windows->Node.js Interactive Window 下找到. Node.js 交互窗口運行后我們要輸入一些命令檢查是否一切OK.

Figure 1 Node.js Interactive Window

現(xiàn)在我們已經(jīng)對安裝進行了驗證,我們現(xiàn)在就可以準備開始創(chuàng)建支持GB級文件上傳的Node.js后臺程序了. 開始我們先創(chuàng)建一個新的項目,并選擇一個空的 Node.js Web應用程序模板.

Figure 2 New project using the Blank Node.js Web Application template

項目創(chuàng)建好以后,我們應該會看到一個叫做 server.js 的文件,還有解決方案瀏覽器里面的Node包管理器 (npm).

圖3 解決方案管理器里面的 Node.js 應用程序

server.js 文件里面有需要使用Node.js來創(chuàng)建一個基礎的hello world應用程序的代碼.

Figure 4 The Hello World application

我現(xiàn)在繼續(xù)把這段代碼從 server.js 中刪除,然后在Node.js中穿件G級別文件上傳的后端代碼。下面我需要用npm安裝這個項目需要的一些依賴:

  •  Express - Node.js網(wǎng)頁應用框架,用于構(gòu)建單頁面、多頁面以及混合網(wǎng)絡應用

  •  Formidable - 用于解析表單數(shù)據(jù),特別是文件上傳的Node.js模塊

  •  fs-extra - 文件系統(tǒng)交互模塊

圖5 使用npm安裝所需模塊

模塊安裝完成后,我們可以從解決方案資源管理器中看到它們。

圖6 解決方案資源管理器顯示已安裝模塊

下一步我們需要在解決方案資源管理器新建一個 "Scripts" 文件夾并且添加  "workeruploadchunk.js" 和   "workerprocessfile.js" 到該文件夾。我們還需要下載 jQuery 2.x 和  SparkMD5 庫并添加到"Scripts"文件夾。 ***還需要添加 "Default.html" 頁面。這些都在我之前的 post 中介紹過。

#p#

創(chuàng)建Node.js后臺

首先我們需要用Node.js的"require()"函數(shù)來導入在后臺上傳G級文件的模塊。注意我也導入了"path"以及"crypto" 模塊。"path"模塊提供了生成上傳文件塊的文件名的方法。"crypto" 模塊提供了生成上傳文件的MD5校驗和的方法。

 
 
  1. // The required modules        
  2. var   express = require('express');      
  3. var   formidable = require('formidable');      
  4. var   fs = require('fs-extra');      
  5. var   path = require('path');  
  6. var   crypto = require('crypto');

下一行代碼就是見證奇跡的時刻。

 
 
  1. var app = express();

這行代碼是用來創(chuàng)建express應用的。express應用是一個封裝了Node.js底層功能的中間件。如果你還記得那個由Blank Node.js Web應用模板創(chuàng)建的"Hello World" 程序,你會發(fā)現(xiàn)我導入了"http"模塊,然后調(diào)用了"http.CreateServer()"方法創(chuàng)建了 "Hello World" web應用。我們剛剛創(chuàng)建的express應用內(nèi)建了所有的功能。

現(xiàn)在我們已經(jīng)創(chuàng)建了一個express應用,我們讓它呈現(xiàn)之前創(chuàng)建的"Default.html",然后讓應用等待連接。

 
 
  1. // Serve up the Default.html page  
  2. app.use(express.static(__dirname, { index: 'Default.html' }));      
  3.  
  4. // Startup the express.js application  
  5. app.listen(process.env.PORT || 1337);      
  6.  
  7. // Path to save the files  
  8. var   uploadpath = 'C:/Uploads/CelerFT/';

express應用有app.VERB()方法,它提供了路由的功能。我們將使用app.post()方法來處理"UploadChunk" 請求。在app.post()方法里我們做的***件事是檢查我們是否在處理POST請求。接下去檢查Content-Type是否是mutipart/form-data,然后檢查上傳的文件塊大小不能大于51MB。

 
 
  1. // Use the post method for express.js to respond to posts to the uploadchunk urls and  
  2. // save each file chunk as a separate file  
  3. app.post('*/api/CelerFTFileUpload/UploadChunk*', function(request,response) {      
  4.  
  5.     if (request.method === 'POST') {      
  6.         // Check Content-Type     
  7.         if (!(request.is('multipart/form-data'))){      
  8.             response.status(415).send('Unsupported media type');      
  9.             return;      
  10.         }      
  11.   
  12.         // Check that we have not exceeded the maximum chunk upload size  
  13.         var maxuploadsize =51 * 1024 * 1024;      
  14.  
  15.         if (request.headers['content-length']> maxuploadsize){      
  16.             response.status(413).send('Maximum upload chunk size exceeded');      
  17.             return;      
  18.         }

一旦我們成功通過了所有的檢查,我們將把上傳的文件塊作為一個單獨分開的文件并將它按順序數(shù)字命名。下面最重要的代碼是調(diào)用fs.ensureDirSync()方法,它使用來檢查臨時目錄是否存在。如果目錄不存在則創(chuàng)建一個。注意我們使用的是該方法的同步版本。

 
 
  1. // Get the extension from the file name  
  2. var extension =path.extname(request.param('filename'));      
  3.  
  4. // Get the base file name  
  5. var baseFilename =path.basename(request.param('filename'), extension);      
  6.  
  7. // Create the temporary file name for the chunk  
  8. var tempfilename =baseFilename + '.'+      
  9. request.param('chunkNumber').toString().padLeft('0', 16) + extension + ".tmp";      
  10.  
  11.  
  12. // Create the temporary directory to store the file chunk  
  13. // The temporary directory will be based on the file name  
  14. var tempdir =uploadpath + request.param('directoryname')+ '/' + baseFilename;      
  15.  
  16. // The path to save the file chunk  
  17. var localfilepath =tempdir + '/'+ tempfilename;      
  18.  
  19. if (fs.ensureDirSync(tempdir)) {      
  20.     console.log('Created directory ' +tempdir);  
  21. }

正如我之前提出的,我們可以通過兩種方式上傳文件到后端服務器。***種方式是在web瀏覽器中使用FormData,然后把文件塊作為二進制數(shù)據(jù)發(fā)送,另一種方式是把文件塊轉(zhuǎn)換成base64編碼的字符串,然后創(chuàng)建一個手工的multipart/form-data encoded請求,然后發(fā)送到后端服務器。

所以我們需要檢查一下是否在上傳的是一個手工multipart/form-data encoded請求,通過檢查"CelerFT-Encoded"頭部信息,如果這個頭部存在,我們創(chuàng)建一個buffer并使用request的ondata時間把數(shù)據(jù)拷貝到buffer中。

在request的onend事件中通過將buffer呈現(xiàn)為字符串并按CRLF分開,從而從 multipart/form-data encoded請求中提取base64字符串。base64編碼的文件塊可以在數(shù)組的第四個索引中找到。

通過創(chuàng)建一個新的buffer來將base64編碼的數(shù)據(jù)重現(xiàn)轉(zhuǎn)換為二進制。隨后調(diào)用fs.outputFileSync()方法將buffer寫入文件中。

 
 
  1. // Check if we have uploaded a hand crafted multipart/form-data request  
  2. // If we have done so then the data is sent as a base64 string  
  3. // and we need to extract the base64 string and save it  
  4. if (request.headers['celerft-encoded']=== 'base64') {     
  5.  
  6.     var fileSlice = newBuffer(+request.headers['content-length']);      
  7.     var bufferOffset = 0;      
  8.  
  9.     // Get the data from the request  
  10.     request.on('data', function (chunk) {      
  11.         chunk.copy(fileSlice , bufferOffset);      
  12.         bufferOffset += chunk.length;      
  13.     }).on('end', function() {      
  14.         // Convert the data from base64 string to binary  
  15.         // base64 data in 4th index of the array  
  16.         var base64data = fileSlice.toString().split('\r\n');      
  17.         var fileData = newBuffer(base64data[4].toString(), 'base64');      
  18.  
  19.         fs.outputFileSync(localfilepath,fileData);      
  20.         console.log('Saved file to ' +localfilepath);      
  21.  
  22.         // Send back a sucessful response with the file name  
  23.         response.status(200).send(localfilepath);      
  24.         response.end();      
  25.     });  
  26. }

二進制文件塊的上傳是通過formidable模塊來處理的。我們使用formidable.IncomingForm()方法得到multipart/form-data encoded請求。formidable模塊將把上傳的文件塊保存為一個單獨的文件并保存到臨時目錄。我們需要做的是在formidable的onend事件中將上傳的文件塊保存為里一個名字。

 
 
  1. else {      
  2.     // The data is uploaded as binary data.      
  3.     // We will use formidable to extract the data and save it      
  4.     var form = new formidable.IncomingForm();      
  5.     form.keepExtensions = true;      
  6.     form.uploadDir = tempdir;     
  7.  
  8.     // Parse the form and save the file chunks to the      
  9.     // default location      
  10.     form.parse(request, function (err, fields, files) {      
  11.         if (err){      
  12.             response.status(500).send(err);      
  13.             return;      
  14.         }      
  15.  
  16.     //console.log({ fields: fields, files: files });      
  17.     });      
  18.  
  19.     // Use the filebegin event to save the file with the naming convention      
  20.     /*form.on('fileBegin', function (name, file) {  
  21.     file.path = localfilepath;  
  22. });*/        
  23.  
  24. form.on('error', function (err) {      
  25.         if (err){      
  26.             response.status(500).send(err);      
  27.             return;      
  28.         }      
  29.     });      
  30.  
  31.     // After the files have been saved to the temporary name      
  32.     // move them to the to teh correct file name      
  33.     form.on('end', function (fields,files) {      
  34.         // Temporary location of our uploaded file             
  35.         var temp_path = this.openedFiles[0].path;      
  36.  
  37.         fs.move(temp_path , localfilepath,function (err){      
  38.  
  39.             if (err) {      
  40.                 response.status(500).send(err);      
  41.                 return;      
  42.             }      
  43.             else {      
  44.                 // Send back a sucessful response with the file name      
  45.                 response.status(200).send(localfilepath);      
  46.                 response.end();      
  47.             }     
  48.         });     
  49.     });      
  50.  
  51. // Send back a sucessful response with the file name      
  52. //response.status(200).send(localfilepath);      
  53. //response.end();      
  54. }  
  55. }

app.get()方法使用來處理"MergeAll"請求的。這個方法實現(xiàn)了之前描述過的功能。

 
 
  1. // Request to merge all of the file chunks into one file  
  2. app.get('*/api/CelerFTFileUpload/MergeAll*', function(request,response) {      
  3.  
  4.     if (request.method === 'GET') {      
  5.  
  6.         // Get the extension from the file name  
  7.         var extension =path.extname(request.param('filename'));      
  8.  
  9.         // Get the base file name  
  10.         var baseFilename =path.basename(request.param('filename'), extension);      
  11.  
  12.         var localFilePath =uploadpath + request.param('directoryname')+ '/' + baseFilename;      
  13.  
  14.         // Check if all of the file chunks have be uploaded  
  15.         // Note we only wnat the files with a *.tmp extension  
  16.         var files =getfilesWithExtensionName(localFilePath, 'tmp')      
  17.         /*if (err) {  
  18.             response.status(500).send(err);  
  19.             return;  
  20.         }*/  
  21.  
  22.         if (files.length !=request.param('numberOfChunks')){     
  23.             response.status(400).send('Number of file chunks less than total count');      
  24.             return;      
  25.         }      
  26.  
  27.         var filename =localFilePath + '/'+ baseFilename +extension;      
  28.         var outputFile =fs.createWriteStream(filename);      
  29.  
  30.         // Done writing the file  
  31.         // Move it to top level directory  
  32.         // and create MD5 hash  
  33.         outputFile.on('finish', function (){      
  34.             console.log('file has been written');      
  35.             // New name for the file  
  36.             var newfilename = uploadpath +request.param('directoryname')+ '/' + baseFilename  
  37.             + extension;      
  38.  
  39.             // Check if file exists at top level if it does delete it  
  40.             //if (fs.ensureFileSync(newfilename)) {  
  41.             fs.removeSync(newfilename);      
  42.             //} 
  43.  
  44.             // Move the file  
  45.             fs.move(filename, newfilename ,function (err) {      
  46.                 if (err) {      
  47.                     response.status(500).send(err);      
  48.                     return;      
  49.                 }      
  50.                 else {      
  51.                     // Delete the temporary directory  
  52.                     fs.removeSync(localFilePath);      
  53.                     varhash = crypto.createHash('md5'),      
  54.                         hashstream = fs.createReadStream(newfilename);     
  55.  
  56.                     hashstream.on('data', function (data) {      
  57.                         hash.update(data)      
  58.                     });      
  59.  
  60.                     hashstream.on('end', function (){     
  61.                         var md5results =hash.digest('hex');      
  62.                         // Send back a sucessful response with the file name  
  63.                         response.status(200).send('Sucessfully merged file ' + filename + ", "      
  64.                         + md5results.toUpperCase());      
  65.                         response.end();      
  66.                     });      
  67.                 }      
  68.             });      
  69.         });      
  70.  
  71.         // Loop through the file chunks and write them to the file  
  72.         // files[index] retunrs the name of the file.  
  73.         // we need to add put in the full path to the file  
  74.         for (var index infiles) {     
  75.             console.log(files[index]);      
  76.             var data = fs.readFileSync(localFilePath +'/' +files[index]);      
  77.             outputFile.write(data);      
  78.             fs.removeSync(localFilePath + '/' + files[index]);      
  79.         }      
  80.         outputFile.end();      
  81.     }  
  82.  
  83. })   ;

注意Node.js并沒有提供String.padLeft()方法,這是通過擴展String實現(xiàn)的。

 
 
  1. // String padding left code taken from  
  2. // http://www.lm-tech.it/Blog/post/2012/12/01/String-Padding-in-Javascript.aspx  
  3. String.prototype.padLeft = function (paddingChar, length) {      
  4.     var s = new String(this);      
  5.     if ((this.length< length)&& (paddingChar.toString().length > 0)) {      
  6.         for (var i = 0; i < (length - this.length) ; i++) {      
  7.             s = paddingChar.toString().charAt(0).concat(s);      
  8.         }      
  9.     }     
  10.     return s;  
  11. }   ;

#p#

一些其它事情

其中一件事是,發(fā)表上篇文章后我繼續(xù)研究是為了通過域名碎片實現(xiàn)并行上傳到CeleFT功能。域名碎片的原理是訪問一個web站點時,讓web瀏覽器建立更多的超過正常允許范圍的并發(fā)連接。 域名碎片可以通過使用不同的域名(如web1.cdxwcx.com,web2.cdxwcx.com)或者不同的端口號(如8000, 8001)托管web站點的方式實現(xiàn)。

示例中,我們使用不同端口號托管web站點的方式。

我們使用 iisnode 把 Node.js集成到 IIS( Microsoft Internet Information Services)實現(xiàn)這一點。 下載兼容你操作系統(tǒng)的版本 iisnode (x86) 或者  iisnode (x64)。 下載 IIS URL重寫包。

一旦安裝完成(假定windows版Node.js已安裝),到IIS管理器中創(chuàng)建6個新網(wǎng)站。將***個網(wǎng)站命名為CelerFTJS并且將偵聽端口配置為8000。

圖片7在IIS管理器中創(chuàng)建一個新網(wǎng)站

然后創(chuàng)建其他的網(wǎng)站。我為每一個網(wǎng)站都創(chuàng)建了一個應用池,并且給應用池“LocalSystem”級別的權(quán)限。所有網(wǎng)站的本地路徑是C:\inetpub\wwwroot\CelerFTNodeJS。

圖片8 文件夾層級

我在Release模式下編譯了Node.js應用,然后我拷貝了server.js文件、Script文件夾以及node_modules文件夾到那個目錄下。

要讓包含 iisnode 的Node.js的應用工作,我們需要創(chuàng)建一個web.config文件,并在其中添加如下得內(nèi)容。

 
 
  1.   
  2.       
  3.         
  4.       
  5.     
  6.  
  7.     
  8.           
  9.       
  10.     
  11.  
  12.     
  13.       
  14.         
  15.           
  16.           
  17.         
  18.  
  19.             
  20.         
  21.           
  22.         
  23.       
  24.   

web.config中各項的意思是讓iisnode處理所有得*.js文件,由server.js 處理任何匹配"/*"的URL。

圖片9 URL重寫規(guī)則

如果你正確的做完了所有的工作,你就可以通過http://localhost:8000瀏覽網(wǎng)站,并進入CelerFT "Default.html"頁面。

web.config文件被修改以支持如前面post中所解釋的大文件的上傳,這里我不會解釋所有的項。不過下面的web.config項可以改善 iisnode中Node.js的性能。

 
 
  1.  node_env="production" debuggingEnabled="false" devErrorsEnabled="false" nodeProcessCountPerApplication="0"&
    當前名稱:使用HTTP上傳G級的文件之Node.js版本
    標題鏈接:http://www.5511xx.com/article/dhpjdid.html