html:
<style>
.wu-example {
position: relative;
padding: 45px 15px 15px;
margin: 15px 0;
background-color: #fafafa;
box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
border-color: #e5e5e5 #eee #eee;
border-style: solid;
border-width: 1px 0;
}
#picker {
display: inline-block;
line-height: 1.428571429;
vertical-align: middle;
margin: 0 12px 0 0;
}
#picker .webuploader-pick {
padding: 6px 12px;
display: block;
}
</style>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")
<link rel="stylesheet" type="text/css" href="~/Scripts/webuploader/webuploader.css">
<script type="text/javascript" src="~/Areas/DataCenter/Content/layer/layer.js"></script>
<script type="text/javascript" src="~/Areas/DataCenter/Content/js/dcommon.js"></script>
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker">选择文件</div>
<button id="ctlBtn" class="btn btn-default btn-sm">开始上传</button>
<button id="btnReset" class="btn btn-default btn-sm">重置</button>
</div>
</div>
<script type="text/javascript" src="~/Scripts/webuploader/webuploader.js"></script>
<script>
$(document).ready(function () {
var GUID = WebUploader.Base.guid();
var uploader = WebUploader.create({
// swf文件路径
swf: '/scripts/webuploader/Uploader.swf',
// 文件接收服务端。
server: '/dbc/Uptest',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
//禁用拖拽上传
disableGlobalDnd: true,
// 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false,
//分片
chunked: true,
//每片大小 2M
chunkSize: 2097152,
//单片失败后重试次数
chunkRetry: 5,
//上传并发线程数
threads: 1,
//可上传文件数量
fileNumLimit: 1,
//图片上传之前不压缩
compress: false,
formData: { guid: GUID }
});
// 当有文件被添加进队列的时候
uploader.on('fileQueued', function (file) {
$('#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) {
accecpResult(response, function () {
$('#' + file.id).find('p.state').html('已上传:<a href=/dbc/getfile?url={0} target=_blank>{0}</a>'.format(response.data));
})
});
uploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
});
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
$('#ctlBtn').on('click', function () {
uploader.upload();
});
$('#btnReset').on('click', function () {
uploader.reset();
$('#thelist').html('');
});
})
</script>
控制器方法:
public JsonResult Uptest()
{
string dirname = "pic";
string path = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!Directory.Exists(path + "/" + dirname))
{
Directory.CreateDirectory(path + "/" + dirname);
}
string guid = Request.Form["guid"];
string id = Request.Form["id"];
string filename = Request.Form["name"];
int chunks = 0, chunk = 0;
if (Request.Form["chunks"] != null)
{
chunks = int.Parse(Request.Form["chunks"]);
chunk = int.Parse(Request.Form["chunk"]);
}
string ext = Path.GetExtension(filename);
string savefile = DateTime.Now.ToFileTime() + ext;
string url = "/" + dirname + "/" + savefile;
HttpPostedFileBase file = Request.Files[0];
if (chunks == 0)
{
//没分片
try
{
file.SaveAs(path + url);
return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok, url));
}
catch (Exception e)
{
return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.err, e.Message));
}
}
else
{
try
{
string gurl = path + "/" + dirname + "/" + guid;
string guidurl = gurl + "/" + id;
if (!Directory.Exists(guidurl))
{
Directory.CreateDirectory(guidurl);
}
string f_index = chunk.ToString() + Path.GetExtension(filename);
file.SaveAs(guidurl + "/" + f_index);
if (chunk == chunks - 1)
{
string targetPath = path + url;
for (int i = 0; i < chunks; i++)
{
using (FileStream addFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write))
{
BinaryWriter bWriter = new BinaryWriter(addFile);
FileInfo fi = new FileInfo(guidurl + "/" + i + Path.GetExtension(filename));
Stream stream = fi.Open(FileMode.Open);
BinaryReader tempReader = new BinaryReader(stream);
bWriter.Write(tempReader.ReadBytes((int)stream.Length));
tempReader.Close();
stream.Close();
}
}
DeleteFolder(gurl);
return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok, url));
}
else
{
return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.ok));
}
}
catch (Exception e)
{
return Json(Dcampus.Areas.DataCenter.DAL.Common.Msg(Common.AjaxStatu.err, e.Message));
}
}
}
private static void DeleteFolder(string strPath)
{
//删除这个目录下的所有子目录
if (Directory.GetDirectories(strPath).Length > 0)
{
foreach (string fl in Directory.GetDirectories(strPath))
{
Directory.Delete(fl, true);
}
}
//删除这个目录下的所有文件
if (Directory.GetFiles(strPath).Length > 0)
{
foreach (string f in Directory.GetFiles(strPath))
{
System.IO.File.Delete(f);
}
}
Directory.Delete(strPath, true);
}
public FileResult GetFile(string url)
{
var path = System.Configuration.ConfigurationManager.AppSettings["UploadPath"] + url;
var filename = Path.GetFileName(path);
return File(path, "application/octet-stream", filename);
}