【发布时间】:2019-11-03 23:00:56
【问题描述】:
我有 FileUploadController 的 asp.net 核心服务器(使用 .net 核心 2.2),它监听传入文件的发布请求。
[HttpPost("Upload")]
// public async Task<IActionResult> Upload([FromForm(Name="file")]IFormFile file) {
// public async Task<IActionResult> Upload([FromForm]IFormFile file) {
public async Task<IActionResult> Upload(IFormFile file) {
Console.WriteLine("***" + file);
if(file == null) return BadRequest("NULL FILE");
if(file.Length == 0) return BadRequest("Empty File");
Console.WriteLine("***" + host.WebRootPath);
if (string.IsNullOrWhiteSpace(host.WebRootPath))
{
host.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
if (!Directory.Exists(uploadsFolderPath)) Directory.CreateDirectory(uploadsFolderPath);
var fileName = "Master" + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadsFolderPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok("Okay");
}
我创建了 Angular 应用程序(使用 Angular 版本 8),它可以选择要在 ClientApplication 上传的文件,并且我创建了三个调用 API“http://localhost:5000/api/fileupload/upload”的 post 服务。
-
标准 Angular HttpClient 帖子。服务器读取时,IFormFile 为空。
const formData: FormData = new FormData(); formData.append('file', file, file.name); // return this.http.post(this.endpoint, file); return this.http.post(this.endpoint, formData); // Problem solved
-
添加了 HttpHeaders,我尝试了空头、未定义和其他来自 stackoverflow 和 google 的建议解决方案。
const header = new HttpHeaders() //1 header.append('enctype', 'multipart/form-data'); //2 header.append('Content-Type', 'multipart/form-data'); //3
如果我在请求中放入带有资源的 httpheader,服务器会给出 415(不支持的媒体类型)
-
我尝试来自 '@angular/common/http' 的 HttpRequest,它最终给了我想要的结果。
const formData: FormData = new FormData(); formData.append('file', file, file.name); const req = new HttpRequest('POST', this.endpoint, formData); return this.http.request(req);
我想知道这是一个错误还是我的误解?如果您查看在线教程,大多数开发人员使用“this.HttpClient.post”。 根据我的阅读,我可以使用 httpclient.post 并且 Angular 框架会自动为用户设置正确的标题。它似乎没有做这项工作。
经过排查,第一个错误是我使用文件的错误 而不是formData,第二个错误是标题“内容类型”声明 httpinterceptor 删除后,它会按预期加载文件。
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
// if (request.url.indexOf('/upload')) {
// return next.handle(request);
// }
const token = localStorage.getItem('token');
const currentUser = JSON.parse(localStorage.getItem('user'));
if (currentUser && token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
// 'Content-Type': 'application/json' <---- Main Problem.
}
});
}
return next.handle(request).pipe(catchError(err => this.handleError(err)));
}
}
【问题讨论】:
-
试试这个:
public async Task<IActionResult> Upload([FromForm] IFormFile file) {} -
@PrashantPimpale 我已经尝试过使用 FromForm 属性,我仍然无法上传它
标签: c# angular typescript asp.net-core angular8