先画html页面:
<div id="uploader" class="wu-example">
<div id="thelist" class="uploadr-list"></div>
<div class="btns">
<div id="picker">选择文件</div>
<button id="ctilBtn" class="btn btn-default">上传</button>
</div>
</div>
js:
初始化webuploader:
var uploader = WebUploader.create({
// swf文件路径
swf: "../node_modules/webuploader/dist/Uploader.swf",
// 文件接收服务端。
server: serverURL + 'Helper/HandlerHelper.ashx',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: { id: '#picker', multiple: false },
//fileVal:'Files', //参数名称
chunked: true,
// 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false,
fileSingleSizeLimit: 4572213932, //大小限制,默认是undefined
chunkSize: 180 * 1024, //分片大小
threads: 1, //上传并发数。允许同时最大上传进程数。
duplicate: false, //可重复上传
chunkRetry: true,
formData: {
'subjectID': getUrlParam('subjectID'), //不需要参数可以不传
}
});
要做一些其他处理的话,可以写在js里的监听事件里:
function listenForUpload(){
$("#ctilBtn").on('click', function () {
uploader.options.formData.smallSubjectID = $('#smallTitle').val(),
uploader.options.formData.folderType = $('#folderType').val(),
uploader.options.formData.mainContent = $('#mainContent').text()
uploader.upload();
});
// 当有文件被添加进队列的时候
uploader.on('fileQueued', function (file) {
//if ($('#thelist').text() != '') {
// var oldFileID = $('#thelist').firstChild.id;
// uploader.removeFile(oldFileID, true);
// $('#thelist').empty();
//}
$('#thelist').html('');
$('#thelist').append( '<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>' );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo( $li ).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css( 'width', percentage * 100 + '%' );
});
uploader.on('uploadSuccess', function (file,response) {
$('#' + file.id).find('p.state').text('已上传');
uploadID.push(response);
});
uploader.on( 'uploadError', function( file ) {
$( '#'+file.id ).find('p.state').text('上传出错');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').fadeOut();
});
}
后台用一般处理程序ashx来接收文件
HandlerHelper.ashx:
分片上传时,这个方法会调用很多次,如果有一些需要保存的信息,可以写在外面的静态变量里,就不会每次都置初始值了
static string fileName = "";
static int dbID;
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.ContentType = "text/plain";
HttpPostedFile file = context.Request.Files[0];
int chunks = 0, chunk = 0;
if (context.Request.Form["chunks"] != null)
{
chunks = int.Parse(context.Request.Form["chunks"]);
chunk = int.Parse(context.Request.Form["chunk"]);
//这个chunk可以记录当前分片是第几次
}
if (chunks != 0)
{
string extension = System.IO.Path.GetExtension(file.FileName);
//这个名字就随便建一个
string fileTempPath = "fdsdfsdf/dfs"
//第一次保存
if (chunk == 0)
{
if (!Directory.Exists(fileTempPath))
{
Directory.CreateDirectory(fileTempPath);
}
Random random = new Random();
string fileNameRandom = random.Next() + extension;
fileName = fileNameRandom;
fileTempPath += fileNameRandom;
//这个ID值是用来存表的,如果不需要ID值可以不存
dbID = AddfileToDB(file, fileNameRandom, fileTempPath);
context.Response.Write(dbID);
return;
}
//追加,这里就是第二次开始往后分片上传的地方
using (FileStream addFile = new FileStream(fileTempPath+fileName, FileMode.Append, FileAccess.Write))
{
BinaryWriter bWriter = new BinaryWriter(addFile);
Stream stream = file.InputStream;
BinaryReader tempReader = new BinaryReader(stream);
bWriter.Write(tempReader.ReadBytes((int)stream.Length));
tempReader.Close();
stream.Close();
}
//如果需要返回给前台,最好每次都返回,防止上传中途出错
context.Response.Write(dbID);
}
}