WebApi實現單個文件的上傳下載

上傳和下載是很經常使用的功能了,只有當用到的時候才發現不會寫...,通過一番百度、篩選、整理修改後,實現了功能,下面簡單的記錄下實現方法。html

1、上傳功能前端

1.前端代碼web

上傳文件 <input type="file" id="file" />
<input type="button" id="upload" value="上傳文件" />

<script>
    //上傳
    $("#upload").click(function () {
        var formData = new FormData();
        var file = document.getElementById("file").files[0];
        formData.append("fileInfo", file);
        $.ajax({
            url: "../api/File/UploadFile",
            type: "POST",
            data: formData,
            contentType: false,//必須false纔會自動加上正確的Content-Type
            processData: false,//必須false纔會避開jQuery對 formdata 的默認處理,XMLHttpRequest會對 formdata 進行正確的處理
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("上傳失敗!");
            }
        });
    });
</script>

2.後臺代碼ajax

 1         /// <summary>
 2         /// 上傳文件
 3         /// </summary>
 4         [HttpPost]
 5         public string UploadFile()
 6         {
 7             string result = string.Empty;
 8             try
 9             {
10                 string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/");
11                 HttpRequest request = System.Web.HttpContext.Current.Request;
12                 HttpFileCollection fileCollection = request.Files;
13                 // 判斷是否有文件
14                 if (fileCollection.Count > 0)
15                 {
16                     // 獲取文件
17                     HttpPostedFile httpPostedFile = fileCollection[0];
18                     string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件擴展名
19                     string fileName = Guid.NewGuid().ToString() + fileExtension;// 名稱
20                     string filePath = uploadPath + httpPostedFile.FileName;// 上傳路徑
21                     // 若是目錄不存在則要先建立
22                     if (!Directory.Exists(uploadPath))
23                     {
24                         Directory.CreateDirectory(uploadPath);
25                     }
26                     // 保存新的文件
27                     while (File.Exists(filePath))
28                     {
29                         fileName = Guid.NewGuid().ToString() + fileExtension;
30                         filePath = uploadPath + fileName;
31                     }
32                     httpPostedFile.SaveAs(filePath);
33                     result = "上傳成功";
34                 }
35             }
36             catch (Exception)
37             {
38                 result = "上傳失敗";
39             }
40             return result;
41         }

 

2、下載功能後端

1.前端代碼api

 1 <form action="../api/File/DownloadFile" method="get" id="form">
 2    下載文件 <input type="text" id="name" name="fileName" value="222" />
 3 </form>
 4 <input type="button" id="download" value="下載文件" />
 5 
 6 <script>
 7     //下載
 8     $("#download").click(function () {
 9         var form = $("#form");
10         form.submit();
11     });
12 </script>

2.後臺代碼跨域

 1         /// <summary>
 2         /// 下載文件
 3         /// </summary>
 4         [HttpGet]
 5         public void DownloadFile()
 6         {
 7             var request = HttpContext.Current.Request;
 8             NameValueCollection nvCollection = request.Params;
 9             string fileName = nvCollection.GetValues("fileName")[0];
10             string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
11             if (File.Exists(filePath))
12             {
13                 HttpResponse response = HttpContext.Current.Response;
14                 response.Clear();
15                 response.ClearHeaders();
16                 response.ClearContent();
17                 response.Buffer = true;
18                 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
19                 response.Charset = "GB2312";
20                 response.ContentEncoding = Encoding.GetEncoding("GB2312");
21                 response.ContentType = MimeMapping.GetMimeMapping(fileName);
22                 response.WriteFile(filePath);
23                 response.Flush();
24                 response.Close();
25             }
26         }

 

3、遇到的問題app

1.寫了個測試的html頁,如何讓程序運行時打開這個頁面,在默認執行的HomeControler中添加劇定向代碼測試

HttpContext.Response.Redirect("Html/Index.html", true);

 2.跨域問題ui

當問題1中html頁和後端程序分開部署時,就會產生跨域問題

可在web.config中進行以下配置

1   <system.webServer>
2     <httpProtocol>
3       <customHeaders>
4         <add name="Access-Control-Allow-Origin" value="*"/>
5         <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type,Accept,Origin"/>
6         <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
7       </customHeaders>    
8     </httpProtocol>
9   </system.webServer>

詳情可閱讀:http://www.javashuo.com/article/p-eegskrpp-eb.html

Demo下載:https://pan.baidu.com/s/1zV1-4WvrP3ZTWwTDFAmExQ

相關文章
相關標籤/搜索