C# 使用Angular 8和.Net Core Web API上载大型文件
我正在尝试将大型文件上载到服务器目录,使用.NETCoreWebAPI作为后端,Angular8作为前端 上传组件.tsC# 使用Angular 8和.Net Core Web API上载大型文件,c#,asp.net,.net,angular,angular8,C#,Asp.net,.net,Angular,Angular8,我正在尝试将大型文件上载到服务器目录,使用.NETCoreWebAPI作为后端,Angular8作为前端 上传组件.ts import { Component } from '@angular/core'; import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http' @Component({ selector: 'app-uploader', templateU
import { Component } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'
@Component({
selector: 'app-uploader',
templateUrl: './uploader.component.html',
})
export class UploadComponent {
public progress: number;
public message: string;
constructor(private http: HttpClient) { }
upload(files) {
if (files.length === 0)
return;
const formData = new FormData();
for (let file of files)
formData.append(file.name, file);
const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
reportProgress: true,
});
this.http.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response)
this.message = event.body.toString();
});
}
}
上传组件HTML
<input #file type="file" multiple (change)="upload(file.files)" />
<br />
<span style="font-weight:bold;color:green;" *ngIf="progress > 0 && progress < 100">
{{progress}}%
</span>
<span style="font-weight:bold;color:green;" *ngIf="message">
{{message}}
</span>
<p><progress showValue="true" type="success" value={{progress}} max="100"></progress></p>
这对于小文件很好。但是当涉及到大文件时,控件永远不会传递给Web控制器。控制台中存在此错误
我认为问题在于.net核心配置中的
requestLimits->maxAllowedContentLength
属性。添加了一个web.config
文件,其中包含
。。仍然无法工作…@techno,您是否将[RequestFormLimits(MultipartBodyLengthLimit=209715200)]添加到您的控制器中?您尝试过这个吗?
namespace WebApplication2.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class UploadController : Controller
{
private IHostingEnvironment _hostingEnvironment;
public UploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Json("Upload Successful.");
}
catch (System.Exception ex)
{
return Json("Upload Failed: " + ex.Message);
}
}
}
}