Jquery fileupload和nodejs实现文件异步上传

通过jquery fileupload插件和nodejs formidable插件实现文件异步上传,并且可以显示文件上传的进度。

1、插件准备

      jquery fileuplaod:下载地址:https://github.com/blueimp/jQuery-File-Upload/tags

     formidable:下载及安装:https://github.com/felixge/node-formidable

     源码中使用了Express框架:https://github.com/visionmedia/express

2、前端代码

      先上一个上传的页面

        图中“异步上传“的选择文件Element的ID为fileupload,因为使用了jquery fileupload插件,js代码就比较简单了,如下:

[javascript]  view plain copy
  1. $('#fileupload').fileupload({  
  2.        url: '/upload',  
  3.        dataType: 'json',  
  4.        //autoUpload: false,  
  5.        //acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,  
  6.        maxFileSize: 5000000, // 5 MB  
  7.        // Enable image resizing, except for Android and Opera,  
  8.        // which actually support image resizing, but fail to  
  9.        // send Blob objects via XHR requests:  
  10.        disableImageResize: /Android(?!.*Chrome)|Opera/  
  11.            .test(window.navigator.userAgent),  
  12.        previewMaxWidth: 100,  
  13.        previewMaxHeight: 100,  
  14.        previewCrop: true  
  15.    }).on('fileuploadadd'function (e, data) {  
  16.        data.context = $('<div/>').appendTo('#files');  
  17.        $.each(data.files, function (index, file) {  
  18.            var node = $('<p/>')  
  19.                    .append($('<span/>').text(file.name));  
  20.            //if (!index) {  
  21.            //    node  
  22.            //        .append('<br>')  
  23.            //        .append(uploadButton.clone(true).data(data));  
  24.            //}  
  25.            node.appendTo(data.context);  
  26.        });  
  27.    }).on('fileuploadprocessalways'function (e, data) {  
  28.        var index = data.index,  
  29.            file = data.files[index],  
  30.            node = $(data.context.children()[index]);  
  31.        if (file.preview) {  
  32.            node  
  33.                .prepend('<br>')  
  34.                .prepend(file.preview);  
  35.        }  
  36.        if (file.error) {  
  37.            node  
  38.                .append('<br>')  
  39.                .append($('<span class="text-danger"/>').text(file.error));  
  40.        }  
  41.        if (index + 1 === data.files.length) {  
  42.            data.context.find('button')  
  43.                .text('Upload')  
  44.                .prop('disabled', !!data.files.error);  
  45.        }  
  46.    }).on('fileuploadprogressall'function (e, data) {  
  47.        var progress = parseInt(data.loaded / data.total * 100, 10);  
  48.        $('#progress .progress-bar').css(  
  49.            'width',  
  50.            progress + '%'  
  51.        );  
  52.    }).on('fileuploaddone'function (e, data) {  
  53.        $.each(data.result.files, function (index, file) {  
  54.            if (file.url) {  
  55.                var link = $('<a>')  
  56.                    .attr('target''_blank')  
  57.                    .prop('href', file.url);  
  58.                $(data.context.children()[index])  
  59.                    .wrap(link);  
  60.            } else if (file.error) {  
  61.                var error = $('<span class="text-danger"/>').text(file.error);  
  62.                $(data.context.children()[index])  
  63.                    .append('<br>')  
  64.                    .append(error);  
  65.            }  
  66.        });  
  67.    }).on('fileuploadfail'function (e, data) {  
  68.        $.each(data.files, function (index, file) {  
  69.            var error = $('<span class="text-danger"/>').text('File upload failed.');  
  70.            $(data.context.children()[index])  
  71.                .append('<br>')  
  72.                .append(error);  
  73.        });  
  74.    }).prop('disabled', !$.support.fileInput)  
  75.        .parent().addClass($.support.fileInput ? undefined : 'disabled');  


3、服务端代码

     基于Node平台,使用formidable插件,轻松实现文件上传,上传的文件保存在了tmp/文件夹下,如下:

[javascript]  view plain copy
  1. exports.upload = function(req, res) {  
  2.     // parse a file upload  
  3.     var form = new formidable.IncomingForm(),files=[],fields=[],docs=[];  
  4.     console.log('start upload');  
  5.       
  6.     //存放目录  
  7.     form.uploadDir = 'tmp/';  
  8.   
  9.     form.on('field'function(field, value) {  
  10.         //console.log(field, value);  
  11.         fields.push([field, value]);  
  12.     }).on('file'function(field, file) {  
  13.         console.log(field, file);  
  14.         files.push([field, file]);  
  15.         docs.push(file);  
  16.   
  17.   
  18.         var types = file.name.split('.');  
  19.         var date = new Date();  
  20.         var ms = Date.parse(date);  
  21.         fs.renameSync(file.path, "tmp/files" + ms + '_'+file.name);  
  22.     }).on('end'function() {  
  23.         console.log('-> upload done');  
  24.         res.writeHead(200, {  
  25.             'content-type''text/plain'  
  26.         });  
  27.         var out={Resopnse:{  
  28.             'result-code':0,  
  29.             timeStamp:new Date(),  
  30.         },  
  31.         files:docs  
  32.         };  
  33.         var sout=JSON.stringify(out);  
  34.         res.end(sout);  
  35.     });  
  36.   
  37.     form.parse(req, function(err, fields, files) {  
  38.         err && console.log('formidabel error : ' + err);  
  39.   
  40.         console.log('parsing done');  
  41.     });  
  42.   
  43. };  

这样就实现了文件的异步上传,点击下载源码

延伸阅读


▶ Walkthrough007

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值