Asp.net MVC 中文件的上传 下载与压缩
这篇文章主要说如何在Asp.net MVC中上传文件并压缩,然后如何再从服务器中把上传过的文件下载下来。
使用FileUpload进行操作:
前端代码:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="/Default/Upload" enctype="multipart/form-data" method="post">
<input id="File1" type="file" name="files" />
<input id="Submit1" type="submit" value="上传" />
<a href="/Default/Download">下载</a>
</form>
后端代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ICSharpCode.SharpZipLib.Zip; //引用该控件压缩文件
using Newtonsoft.Json;
namespace WebApplication1.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public ActionResult Upload(HttpPostedFileBase files) //充当类的基类,提供对客户端已上传单独文件的访问
{
//判断传过来的值是否为空
if (files == null)
{
//返回提示
Response.Write("<script>alert('不可以为空');</script>");
return View();
}
else
{
//定义一个文件大小的最大值
int MaxContentLength = 1024 * 25;
//判断 如果上传文件的大小超过最大值
if (files.ContentLength > MaxContentLength)
{
//返回提示
return Content("<script>alert('上传超过25M,不能上传');</script>");
}
else
{
//获取客户端上文件的名称
string name = Path.GetFileName(files.FileName);
//返回web服务器上指定虚拟路径相对应的物理路径
string path = Server.MapPath("~/Upload");
//将两个字符串组合为一个路径
string txtPath = Path.Combine(path, name);
//在派生类中重写时,保存上传文件的内容
files.SaveAs(txtPath);
//返回一个新字符串将所有指定字符串替换为另一个指定的字符串
string newName = name.Replace("txt", "zip");
//压缩zip
using (ZipFile zip = ZipFile.Create(newName))
{
zip.BeginUpdate();
zip.Add(txtPath);
zip.CommitUpdate();
}
//将路径保存在服务端
Session["txtPath"] = txtPath;
//将文件名保存在服务端
Session["name"] = name;
//返回正确提示
return Content("<script>alert('上传成功');</script>");
}
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <returns></returns>
public ActionResult Download()
{
string path = Session["txtPath"].ToString();
string name = Session["name"].ToString();
FileStream file = new FileStream(path, FileMode.Open);
string str = MimeMapping.GetMimeMapping(path);
return File(file, str, name);
}
}
}
效果图: