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.
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.
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.
Our configuration part is over. Now, let’s create a new API controller.
We can add the below code to this controller.
- public class FileuploadController : ApiController
- {
- public async Task<bool> Upload()
- {
- try
- {
- var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
- 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);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- }
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.
We can click the “Send” button now. After some time, we will get a 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).
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.
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.
We can click the “Send” button now. After some time, we will get a 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).
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.
- //Code for renaming the random file to Original file name
- 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);
- //Code renaming ends...
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).
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>
<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:
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