2020-07-22

C#:使用ajax异步请求实现文件上传与下载功能。

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 的默认处理,   success: function(data) {   if (data.Code == 0)    alert(data.Msg)    else    alert(data.Url)   },   error: function(data) {   alert("上传失败!");  } });}</script>

 

C#:使用ajax异步请求实现文件上传与下载功能。patpat败欧洲e淘网武汉病毒所致全所职工:若干谣言伤害极大 问心无愧亚马逊大规模封号又来了!别慌,这样处理救回你的账号!亚马逊被美国政府制裁!卖家有了新保障品读东欧街头巷尾的那些文艺范(2)徽杭古道徒步旅行游记_临安攻略好色之途 追随最后一抹绚烂秋色(5)

No comments:

Post a Comment