.Net中MVC实现上传与下载
视图层界面:
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<h2>上传文件</h2>
<br />
@*new {enctype = "multipart/form-data"}将表单设置成允许文件上传或下载*@
@using (Html.BeginForm("Upload","Home", FormMethod.Post,new {enctype = "multipart/form-data"}))
{
<text>选择上传文件:</text>
<input name="file" type="file" id="file"/>
<br />
<input type="submit" name="upload" value="上传"/>
}
<br />
<br />
<div>
<a href="/Home/DownLoad?filepath=@ViewBag.value&filename='2.jpg'">图片2</a><br />
<a href="/Home/DownLoad?filepath=@ViewBag.value&filename='新建文本文档.txt'">文档</a>
</div>
控制层代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.value = Server.MapPath("~/File/Upload/");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Upload()
{
if (Request.Files.Count==0)
{
return Content("请选择上传文件");
}
var file = Request.Files[0];
if (file.ContentLength==0)
{
return Content("请选择存在的文件");
}
else
{
string target = Server.MapPath("/") + "File/Upload/";
string filename = file.FileName;
file.SaveAs(target + filename);
return Content("上传成功");
}
}
public ActionResult DownLoad(string filepath,string filename)
{
Encoding encoding;
string downloadfile = null;
filename = filename.Replace("'", "");
string browser = Request.UserAgent.ToUpper();
downloadfile = HttpUtility.UrlEncode(filename);
encoding = Encoding.GetEncoding("GB2312");
//if (browser.Contains("FIREFOX"))
//{
//}
//else
//{
// downloadfile = HttpUtility.UrlEncode(filename);
// encoding = Encoding.Default;
//}
FileStream fs=new FileStream(filepath+filename, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Response.Charset = "UTF-8";
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = encoding;
Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadfile);
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
return Content("下载完成!");
}
}
}
演示:
我这里下载的是指定的文件图片2