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代碼就比較簡單了,如下:

 $('#fileupload').fileupload({
        url: '/upload',
        dataType: 'json',
        //autoUpload: false,
        //acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 5000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 100,
        previewMaxHeight: 100,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        data.context = $('<div/>').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<p/>')
                    .append($('<span/>').text(file.name));
            //if (!index) {
            //    node
            //        .append('<br>')
            //        .append(uploadButton.clone(true).data(data));
            //}
            node.appendTo(data.context);
        });
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append($('<span class="text-danger"/>').text(file.error));
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            if (file.url) {
                var link = $('<a>')
                    .attr('target', '_blank')
                    .prop('href', file.url);
                $(data.context.children()[index])
                    .wrap(link);
            } else if (file.error) {
                var error = $('<span class="text-danger"/>').text(file.error);
                $(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index, file) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

3、服務端代碼

     基於Node平臺,使用formidable插件,輕鬆實現文件上傳,上傳的文件保存在了tmp/文件夾下,如下:

exports.upload = function(req, res) {
	// parse a file upload
	var form = new formidable.IncomingForm(),files=[],fields=[],docs=[];
	console.log('start upload');
	
	//存放目錄
	form.uploadDir = 'tmp/';

	form.on('field', function(field, value) {
		//console.log(field, value);
		fields.push([field, value]);
	}).on('file', function(field, file) {
		console.log(field, file);
		files.push([field, file]);
		docs.push(file);


		var types = file.name.split('.');
		var date = new Date();
		var ms = Date.parse(date);
		fs.renameSync(file.path, "tmp/files" + ms + '_'+file.name);
	}).on('end', function() {
		console.log('-> upload done');
		res.writeHead(200, {
			'content-type': 'text/plain'
		});
		var out={Resopnse:{
			'result-code':0,
			timeStamp:new Date(),
		},
		files:docs
		};
		var sout=JSON.stringify(out);
		res.end(sout);
	});

	form.parse(req, function(err, fields, files) {
		err && console.log('formidabel error : ' + err);

		console.log('parsing done');
	});

};

這樣就實現了文件的異步上傳,點擊下載源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章