我有一个具有FileUploadController的asp.net核心服务器(使用.net core 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");
}
我创建了角度应用程序(使用角度版本8),该应用程序可以选择要在ClientApplication上载的文件,并且我创建了三个调用api“ http://localhost:5000/api/fileupload/upload”的帖子服务。
标准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,第二个错误是标头“ content-type”在 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)));
}
}
答案 0 :(得分:1)
以下代码为您服务
uploadSecond(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post('https://localhost:44393/api/fileupload/UploadSecond', formData);
}
然后在您的控制器中
[HttpPost("UploadSecond")]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadSecond([FromForm]IFormFile file)
答案 1 :(得分:1)
在第一个无效的示例中,您将file
而不是post(...)
传递到formData
中。应该是:
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(this.endpoint, formData);
您为控制器显示的代码似乎正确,因此这应该是唯一需要的更改。您不需要 在从Angular发送的请求上设置任何自定义标头。
答案 2 :(得分:0)
如果在客户端中使用FormData,则可以获取类似的文件。
[HttpPost("Upload"), DisableRequestSizeLimit]
public ActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources","Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}