WebApi realizes the upload and download of single file

Upload and download are very common functions. Only when they are used can they find that they can't write... After a lot of Baidu, filtering, sorting and modification, the function is realized. The following is a simple record of the implementation method.

I. upload function

1. Front end code

Upload files <input type="file" id="file" />
<input type="button" id="upload" value="Upload files" />

<script>
    //upload
    $("#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,//Must false Will automatically add the right Content-Type
            processData: false,//Must false Will avoid jQuery Yes formdata Default processing for, XMLHttpRequest Would be right formdata Do the right thing
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("Upload failed!");
            }
        });
    });
</script>

2. Background code

 1         /// <summary>
 2         /// Upload files
 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                 // Determine whether there are documents
14                 if (fileCollection.Count > 0)
15                 {
16                     // get files
17                     HttpPostedFile httpPostedFile = fileCollection[0];
18                     string fileExtension = Path.GetExtension(httpPostedFile.FileName);// File extension
19                     string fileName = Guid.NewGuid().ToString() + fileExtension;// Name
20                     string filePath = uploadPath + httpPostedFile.FileName;// Upload path
21                     // If the directory does not exist, create it first
22                     if (!Directory.Exists(uploadPath))
23                     {
24                         Directory.CreateDirectory(uploadPath);
25                     }
26                     // Save new file
27                     while (File.Exists(filePath))
28                     {
29                         fileName = Guid.NewGuid().ToString() + fileExtension;
30                         filePath = uploadPath + fileName;
31                     }
32                     httpPostedFile.SaveAs(filePath);
33                     result = "Upload success";
34                 }
35             }
36             catch (Exception)
37             {
38                 result = "Upload failure";
39             }
40             return result;
41         }

 

2. Download function

1. Front end code

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

2. Background code

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

III. problems encountered

1. Write a test html page. How to open this page when the program is running and add redirection code in the default homecontroller

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

2. Cross domain issues

When the html page and back-end program in question 1 are deployed separately, cross domain problems will occur

You can configure it in web.config as follows

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>

Details can be read: https://www.cnblogs.com/landeanfen/p/5177176.html

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

Keywords: C# JQuery encoding

Added by FURQAN on Wed, 11 Dec 2019 02:43:30 +0200