Thứ Tư, 7 tháng 8, 2019

Api upload large file MultiPart in C#

1. Link Tham Khảo:
https://www.c-sharpcorner.com/article/upload-large-files-to-mvc-webapi-using-partitioning/
https://www.c-sharpcorner.com/article/upload-large-files-in-web-api-with-a-simple-method/

2. Hướng dẫn:

We can create a Web API project in Visual Studio 2017/2015. I am using Visual Studio 2017 community edition.

Web API project in Visual Studio 

After some time, our project will be created with default templates.
We must change the value of “maxAllowedContentLength” in “requestLimits” in web configuration file to 1GB. If your upload file size is more than 1GB, please change the settings accordingly.
maxAllowedContentLength 

We gave the value in Bytes.

We must change the settings under system.webServer node in the web.config file.
We can add more settings in the web.config file for the location of our files to be stored.
web.config file 

Our configuration part is over. Now, let’s create a new API controller.

new API controller 

We can add the below code to this controller.
  1. public class FileuploadController : ApiController  
  2.     {  
  3.         public async Task<bool> Upload()  
  4.         {  
  5.             try  
  6.             {  
  7.                 var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];  
  8.   
  9.                 var provider = new MultipartFormDataStreamProvider(fileuploadPath);  
  10.                 var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));  
  11.                 foreach (var header in Request.Content.Headers)  
  12.                 {  
  13.                     content.Headers.TryAddWithoutValidation(header.Key, header.Value);  
  14.                 }  
  15.   
  16.                 await content.ReadAsMultipartAsync(provider);  
  17.   
  18.                 return true;  
  19.             }  
  20.             catch (Exception)  
  21.             {  
  22.                 return false;  
  23.             }  
  24.   
  25.         }  
  26.     }  
We created a provider variable with “MultipartFormDataStreamProvider” and content variable with “StreamContent”. Then we added the Request headers to a content variable using a FOR Loop.
Finally, we read the multi-part data from the content variable asynchronously. It will automatically create a file in the given folder. (We gave the output path as a web configuration parameter)
We can use the postman tool to test our WebAPI. Please run our Web API now. After our Web API loaded, we can come to postman tool and using POST method we can send a request to Web API. We must choose “form-data” in the body part and choose “File” as type.
POST method

We can click the “Send” button now. After some time, we will get a result.
Result 

We got a “true” result. That means, our file upload successfully completed. Now we can check the file location (which we mentioned in the theweb.config file).
location  

Please note though our file uploaded successfully, we got a different random file name in the uupload location without any extension.
We can add one simple step to rename the file name with the original file name.
  1. //Code for renaming the random file to Original file name  
  2.                string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();  
  3.                string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));  
  4.   
  5.                if (File.Exists(originalFileName))  
  6.                {  
  7.                    File.Delete(originalFileName);  
  8.                }  
  9.   
  10.                File.Move(uploadingFileName, originalFileName);  
  11.                //Code renaming ends...  
Please execute the postman with the same file again and see the difference.
Upload Large Files In Web API

Please note, our file successfully uploaded with the original file name. We tested the application with a very small file (less than 2MB).
Now we can test with a large-sized file (File size is 708 MB).
Upload Large Files In Web API
After some time, our large file will be uploaded successfully. You can now check the file upload folder and see the new file there.
Upload Large Files In Web API 
In this article, we saw very simple steps to upload large files in Web APIs. You can use the same code for any large file. As this is a Web API, we can use this with any client-side application (Windows or Web).
 3. Config Large max file size trong web config Visual Studio (Vd max là 250MB):
<system.webServer>
    <security>
      <requestFiltering>
        <!--Add this line: Max= 250MB-->
        <requestLimits maxAllowedContentLength="262144000" />
      </requestFiltering>
    </security>
  </system.webServer>

4. Code (có thay đổi path: tạo new Folder trong dự án tên là Uploaded thay cho cấu hình thư mục FileUploaded ở trên):

//using apiUploadMultipart.Models;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.Http;

namespace apiUploadMultipart.Controllers
{
    public class DocumentUploadController : ApiController
    {
        public async Task<bool> Upload()
        {
            try
            {
                //string tempDocUrl = WebConfigurationManager.AppSettings["DocsUrl"];
                //var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
                //string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
                var path = HttpRuntime.AppDomainAppPath;
                var fileuploadPath = System.IO.Path.Combine(path, "Uploaded");

                var provider = new MultipartFormDataStreamProvider(fileuploadPath);
                var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
                foreach (var header in Request.Content.Headers)
                {
                    content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }

                await content.ReadAsMultipartAsync(provider);

                //--Rename to original fileName
                string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
                string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));

                if (File.Exists(originalFileName))
                {
                    File.Delete(originalFileName);
                }

                File.Move(uploadingFileName, originalFileName);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

5. Test với Postman:

 

//**END**---

Không có nhận xét nào:

Đăng nhận xét