Webupload + MVC 之上传下载
最近工作中用到了 MVC 的上传及下载 , 写下感受
本项目中用到的是百度的webuploader
<!--引入Jquery-->
<script src="~/Content/webUpLoade/jquery-1.11.3.js"></script>
<!--引入CSS-->
<link href="~/Content/webUpLoade/webuploader.css" rel="stylesheet" />
<!--引入JS-->
<script src="~/Content/webUpLoade/webuploader.js"></script>
<script type="text/javascript">
var uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: false,
swf: 'Content/webUpLoade/Uploader.swf',
// 文件接收服务端。
server: '/Home/TextUpdate',
// 开起分片上传 chunkSize {Boolean} [可选] [默认值:5242880] 默认大小为5M.
chunked: true,
//如果某个分片由于网络问题出错,允许自动重传多少次? Defualt 2
chunkRetry: 3,
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
//sendAsBinary: true,//开启二进制
//fileVal: "uploadfile",// 默认file 指明参数名称,后台也用这个参数接收文件
// 文件格式限制
accept: {
title: '文件上传',
extensions: 'rar,doc,xls',
mimeTypes: '.rar,.doc,.xls'
},
method: 'POST',
});
</script>
HTML 代码
<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">开始上传</button>
</div>
</div>
Controller
[HttpPost]
public ActionResult TextUpdate(HttpPostedFileBase file)
{
string filename = file.FileName;
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), file.FileName);
file.SaveAs(path);
return View();
}
2.下载
view 视图
<a href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下载</a>
1、
public ActionResult DownLoad(string path,string fileName)
{
return File(new FileStream(path, FileMode.Open), "application/octet-stream", Server.UrlEncode(fileName));
}
2、
public ActionResult DownFile(string filePath, string fileName)
{
filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return new EmptyResult();
}