欢迎光临
我的个人博客网站

C#:使用ajax异步请求实现文件上传与下载功能。—项目框架API+MVC

1.首先使用VS创建WebAPI项目

(这里有个帮助类,将此帮助类复制到项目里,有兴趣可以学着写)

//文件上传下载,导入导出辅助类  public class APIFileHelp {    //此为限制文件格式   public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png", ".jpg" };    //Upload为自定义的文件夹,在项目中创建   public string UrlPath = "/Upload/";    //响应对象 ,使用前先赋值   public HttpResponse Response = HttpContext.Current.Response;   public HttpRequest Request = HttpContext.Current.Request;    //文件下载   //downFileName下载后保存名,sourceFileName服务器端物理路径   public void DownLoad(string downFileName, string sourceFileName)   {     if (File.Exists(sourceFileName))     {       Response.Clear();       Response.ClearHeaders();       Response.ClearContent();       Response.Buffer = true;       Response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", downFileName));       Response.Charset = "GB2312";       Response.ContentEncoding = Encoding.GetEncoding("GB2312");       Response.ContentType = MimeMapping.GetMimeMapping(downFileName);       Response.WriteFile(sourceFileName);       Response.Flush();       Response.Close();     }       }  //文件上传操作 public FileResult UpLoad() { //保存文件名 string name = ""; if (Request.Files.Count > 0) { string FileUrlResult = ""; foreach (string fn in Request.Files) { var file = Request.Files[fn]; name = file.FileName.ToString(); var extenfilename = Path.GetExtension(file.FileName); //判断 路径是否存在 string path = HttpContext.Current.Server.MapPath(UrlPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }  if (ExtentsfileName.Contains(extenfilename.ToLower())) { string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename; string filepath = HttpContext.Current.Server.MapPath(urlfile); file.SaveAs(filepath); FileUrlResult += urlfile + ";"; }  //格式不正确 else {
  //实例化结果类
return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件" + string.Join(",", ExtentsfileName), Url = "" }; } } //上传成功 return new FileResult() { Code = 0, Name = name, Msg = "上传成功", Url = FileUrlResult }; } //上传失败 else { return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" }; } } } //结果类 public class FileResult { public int Code { get; set; } //结果 public string Msg { get; set; } //提示信息 public string Url { get; set; } //地址 public string Name { get; set; } //文件名 }

//控制器端 public class FileOperationController : ApiController {    
//实例化帮助类 APIFileHelp help
= new APIFileHelp(); [HttpGet] public void DownLoad(string Url) { string filePath = HttpContext.Current.Server.MapPath(Url); FileInfo fi = new FileInfo(filePath); help.DownLoad(fi.Name, fi.FullName); } //文件上传 [HttpPost] public FileResult UpLoad() { return help.UpLoad(); } }

//文件上传、下载: MVC端 
//文件下载 //API地址+参数+自己定义的文件名+文件Url <a href = "https://localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >

<input type = "file" id="f1" />
<input type = "button" value="aa" onclick="ff()"/>  <script>     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("上传失败!");         }     }); } </script>

 

赞(0) 打赏
未经允许不得转载:张拓的天空 » C#:使用ajax异步请求实现文件上传与下载功能。—项目框架API+MVC
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏