设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

使用HTTP上传G级的文件之Node.js版本

2014-11-4 11:34| 发布者: joejoe0332| 查看: 4458| 评论: 0|原作者: LeoXu, 开源中国榨菜, LeoG0816, daxiang, Cath, DYOS|来自: oschina

摘要: 近年来, Javascript越来越流行,这似乎是由于 Javascript 生态系统正在帮助提高生产率、减少入门所需的时间。 在我的 第一篇文章中,我介绍了使用 ASP.NET Web 后端 API 实现 G级文件上传,发表完这篇文章后,我决 ...


  我现在继续把这段代码从 server.js 中删除,然后在Node.js中穿件G级别文件上传的后端代码。下面我需要用npm安装这个项目需要的一些依赖:

  •  Express - Node.js网页应用框架,用于构建单页面、多页面以及混合网络应用

  •  Formidable - 用于解析表单数据,特别是文件上传的Node.js模块

  •  fs-extra - 文件系统交互模块 


图5 使用npm安装所需模块


  模块安装完成后,我们可以从解决方案资源管理器中看到它们。



图6 解决方案资源管理器显示已安装模块


  下一步我们需要在解决方案资源管理器新建一个 "Scripts" 文件夹并且添加  "workeruploadchunk.js" 和   "workerprocessfile.js" 到该文件夹。我们还需要下载 jQuery 2.x 和  SparkMD5 库并添加到"Scripts"文件夹。 最后还需要添加 "Default.html" 页面。这些都在我之前的 post 中介绍过。 


创建Node.js后台

  首先我们需要用Node.js的"require()"函数来导入在后台上传G级文件的模块。注意我也导入了"path"以及"crypto" 模块。"path"模块提供了生成上传文件块的文件名的方法。"crypto" 模块提供了生成上传文件的MD5校验和的方法。

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


  下一行代码就是见证奇迹的时刻。

1
<span style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-removed: initial; background-repeat: initial; background-size: initial; color: #000066; font-family: Consolas; font-size: 9pt;">var</span><span style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-removed: initial; background-repeat: initial; background-size: initial; font-family: Consolas; font-size: 9pt;"> app <span style="color: #339933;">=</span> express<span style="color: #009900;">()</span><span style="color: #339933;">;</span></span>


  这行代码是用来创建express应用的。express应用是一个封装了Node.js底层功能的中间件。如果你还记得那个由Blank Node.js Web应用模板创建的"Hello World" 程序,你会发现我导入了"http"模块,然后调用了"http.CreateServer()"方法创建了 "Hello World" web应用。我们刚刚创建的express应用内建了所有的功能。


  现在我们已经创建了一个express应用,我们让它呈现之前创建的"Default.html",然后让应用等待连接。

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


  express应用有app.VERB()方法,它提供了路由的功能。我们将使用app.post()方法来处理"UploadChunk" 请求。在app.post()方法里我们做的第一件事是检查我们是否在处理POST请求。接下去检查Content-Type是否是mutipart/form-data,然后检查上传的文件块大小不能大于51MB。

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

  一旦我们成功通过了所有的检查,我们将把上传的文件块作为一个单独分开的文件并将它按顺序数字命名。下面最重要的代码是调用fs.ensureDirSync()方法,它使用来检查临时目录是否存在。如果目录不存在则创建一个。注意我们使用的是该方法的同步版本。

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

  正如我之前提出的,我们可以通过两种方式上传文件到后端服务器。第一种方式是在web浏览器中使用FormData,然后把文件块作为二进制数据发送,另一种方式是把文件块转换成base64编码的字符串,然后创建一个手工的multipart/form-data encoded请求,然后发送到后端服务器。 


  所以我们需要检查一下是否在上传的是一个手工multipart/form-data encoded请求,通过检查"CelerFT-Encoded"头部信息,如果这个头部存在,我们创建一个buffer并使用request的ondata时间把数据拷贝到buffer中。


  在request的onend事件中通过将buffer呈现为字符串并按CRLF分开,从而 multipart/form-data encoded请求中提取base64字符串。base64编码的文件块可以在数组的第四个索引中找到。


  通过创建一个新的buffer来将base64编码的数据重现转换为二进制。随后调用fs.outputFileSync()方法将buffer写入文件中。

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

  二进制文件块的上传是通过formidable模块来处理的。我们使用formidable.IncomingForm()方法得到multipart/form-data encoded请求。formidable模块将把上传的文件块保存为一个单独的文件并保存到临时目录。我们需要做的是在formidable的onend事件中将上传的文件块保存为里一个名字。

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



酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部