文件的上传与下载
使用MVC简单实现文件的上传与下载
一、使用Form表单提交上传文件
<form action="@Url.Action("Upload","Default")" method = "post" enctype="multipart/form-data" >
<input type="file" name="file" /><br>
<input type="submit" value="提交" />
</form>
二、下载文件
<a href='@Url.Action("Download","File",new{fileName="MyPhono.jpg"})' />下载文件</a>
三、创建FileContorller.cs后台控制器
public class FileController : Controller
{
/// <summary>
/// 上传文件
/// </summary>
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = file.FileName;
var filePath = Server.MapPath(string.Format("~/{0}", "File"));
file.SaveAs(Path.Combine(filePath, fileName));
return Json("上传成功");
}
/// <summary>
/// 下载文件
/// </summary>
public FileStreamResult Download(string fileName)
{
string filePath = Server.MapPath(string.Format("~/{0}/{1}", "File", fileName));
FileStream fs = new FileStream(filePath, FileMode.Open);
return File(fs, "text/plain", fileName);
}
}
使用JS实现文件的上传与下载
文件上传:
视图 view:
ViewBag.Title = "Index";
}
<h2>文件管理</h2>
<input id="F1" type="file" />
<input id="Button1" type="button" value="上传" onclick="upload()" />
</form>
var data = new FormData();
//获取文件
var file = document.getElementById("F1").files[0];
//添加数据
data.append("F1", file);
$.ajax({
url: '/File/Upload/',
type: 'post',
data: data,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function (d) {
if (d>0) {
alert("上传成功!");
return;
} else {
alert("上传失败!");
return;
}
}
});
}
</script>
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
[HttpPost]
public int Upload()
{
//判断文件是否选中
if (Request.Files.Count>0)
{
//获取文件
var file = HttpContext.Request.Files[0];
//获取上传文件的扩展名
//首先将文件名按.切割
var temp = file.FileName.Split('.');
//获取扩展名
var extendName = temp[temp.Length - 1];
//获取路径
var path = HttpContext.Server.MapPath("~/Upload/");
//判断路径是否存在
if (Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//文件重新命名
var name = DateTime.Now.ToFileTime() + "." + extendName;
//保存上传文件
file.SaveAs(Path.Combine(path, name));
//返回结果
return 1;
}
else
{
return 0;
}
}
/// 下载文件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public FileStreamResult Download(string fileName)
{
string filePath = Server.MapPath(string.Format("~/{0}/{1}", "Upload", fileName));
FileStream fs = new FileStream(filePath, FileMode.Open);
return File(fs, "text/plain", fileName);
}
使用API加MVC实现图片的上传与下载
c# api+mvc实现上传和下载功能(转载)
public class FileResult
{
public int Code { get; set; }
public string Msg { get; set; }
public string Url { get; set; }
}
//首先在api方法内新建一个控制器
//控制器内写关于上传和下载的具体代码
public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png",".jpg" };
[HttpGet]
public void DownLoad(string Url)
{
string filePath = HttpContext.Current.Server.MapPath(Url);
FileInfo fi = new FileInfo(filePath);
if (File.Exists(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = MimeMapping.GetMimeMapping(fi.Name);
response.WriteFile(filePath);
response.Flush();
response.Close();
}
}
[HttpPost]
public FileResult UpLoad()
{
var request = HttpContext.Current.Request;
if (request.Files.Count > 0)
{
var file = request.Files[0];
var extenfilename = Path.GetExtension(file.FileName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
{
string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
string filepath = HttpContext.Current.Server.MapPath(urlfile);
file.SaveAs(filepath);
return new FileResult() { Code = 0, Msg = "上传成功", Url = urlfile };
}
else
{
return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件"+string.Join(",",ExtentsfileName), Url = "" };
}
}
else
{
return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" };
}
}
}
//写完api方法之后写mvc前台
<input type = "button" value="aa" onclick="ff()"/>
function ff()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "https://localhost:44370/api/FileOperation/UpLoad",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(data) {
if (data.Code < 0)
alert(data.Msg)
else
alert(data.Url)
},
error: function(data) {
alert("上传失败!");
}
});
}
<a href = "https://localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >
c# api+mvc实现上传和下载功能(转载)
public class FileResult
{
public int Code { get; set; }
public string Msg { get; set; }
public string Url { get; set; }
}
//首先在api方法内新建一个控制器
//控制器内写关于上传和下载的具体代码
public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png",".jpg" };
[HttpGet]
public void DownLoad(string Url)
{
string filePath = HttpContext.Current.Server.MapPath(Url);
FileInfo fi = new FileInfo(filePath);
if (File.Exists(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = MimeMapping.GetMimeMapping(fi.Name);
response.WriteFile(filePath);
response.Flush();
response.Close();
}
}
[HttpPost]
public FileResult UpLoad()
{
var request = HttpContext.Current.Request;
if (request.Files.Count > 0)
{
var file = request.Files[0];
var extenfilename = Path.GetExtension(file.FileName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
{
string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
string filepath = HttpContext.Current.Server.MapPath(urlfile);
file.SaveAs(filepath);
return new FileResult() { Code = 0, Msg = "上传成功", Url = urlfile };
}
else
{
return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件"+string.Join(",",ExtentsfileName), Url = "" };
}
}
else
{
return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" };
}
}
}
//写完api方法之后写mvc前台
<input type = "button" value="aa" onclick="ff()"/>
function ff()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "https://localhost:44370/api/FileOperation/UpLoad",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(data) {
if (data.Code < 0)
alert(data.Msg)
else
alert(data.Url)
},
error: function(data) {
alert("上传失败!");
}
});
}
<a href = "https://localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >