如何在Angular 6中上传文件时修复415不支持的媒体类型 [英] How can I fix 415 unsupported media type on file upload in Angular 6

查看:171
本文介绍了如何在Angular 6中上传文件时修复415不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.Net Core Web Api和Angular应用程序上工作.我创建了一个控制器,该控制器将图像链接到数据库中的项目:

I work on a .Net Core Web Api and an Angular application. I created a controller which links an image to an item in database:

[HttpPut("[Action]/{id}")]
public async Task<ActionResult<Item>> LinkItemToIcon(int id, IFormFile file)
{
    var items = await _context.Items.FirstOrDefaultAsync(t => t.Id == id);

    if (items == null)
    {
        return BadRequest("item null");
    }

    if (file.Length <= 0)
    {
        return BadRequest("fileEmpty");
    }

    using (var memoryStream = new MemoryStream())
    {
        await file.CopyToAsync(memoryStream);
        Item item = new Item() { Id = items.Id, Icon = memoryStream.ToArray() };
        _context.Entry(items).CurrentValues.SetValues(item);
        _context.SaveChanges();

        return Ok(file);
    }
}

它在Postman中运行良好,但是当我想使用控制器时,出现错误消息:

It works well in Postman, but when I want to use the controller, I get an error:

标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,标头:Map(0)} 消息:" https://localhost:5001/api/LinkItemToIcon :415不支持的媒体类型"
名称:"HttpErrorResponse"
好的:错误
状态:415
statusText:不支持的媒体类型"
url:" https://localhost:5001/api/LinkItemToIcon "

Headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: "Http failure response for https://localhost:5001/api/LinkItemToIcon: 415 Unsupported Media Type"
name: "HttpErrorResponse"
ok: false
status: 415
statusText: "Unsupported Media Type"
url: "https://localhost:5001/api/LinkItemToIcon"

您可以在我的角度应用程序中看到我的html:

You can see my html in my angular application :

<input type="file" (change)="onSelectedFile($event) name="file">
<input type="button" (click)="linkItem()">

您可以看到我的组件:

this.selectedFile : File = null ;
onSelectedFile(e){
    this.selectedFile = e.target.files[0]
}
LinkItem(){
    var formData = new FormData();
    formData.append("file",this.selectedFile, this.selectedFile.name)
    this.administrator.LinkItemToIcon(1,formData).subscribe(
       r => console.log(r),
       err => console.log(err)
    )
}

现在我的服务:

  LinkItemToIcon(id,file){
return this.http.put<UploadFile>(`${this.config.catchApiUrl()}Item/LinkItemToIcon/`+ id, file
,{
  headers : new HttpHeaders({
    'Content-Type' : 'application/json'
  })}
)

}

我的断点结果:

想想您的帮助. 断点结果

当我想订阅linkItemToIcon时出现错误消息

And I have an error message when I want to subscribe to linkItemToIcon

未定义FormData

FormData is not defined

此外,我可以在我的代码中将应用程序/json的内容类型更改为multipart/form-data,因为我有

Moreover I can change in my code my content-type which is application/json to multipart/form-data because I have an

PUT https://localhost:5001/api/Item/LinkItemToIcon/1 500(内部服务器错误)

PUT https://localhost:5001/api/Item/LinkItemToIcon/1 500 (Internal Server Error)

通过" https://localhost:5001/api/Item/Link/LinkItemToIcon/访问XMLHttpRequest 1 "(来自来源" http://localhost:4200 )已被CORS政策阻止:否' Access-Control-Allow-Origin'标头出现在所请求的资源上.

Access to XMLHttpRequest at 'https://localhost:5001/api/Item/LinkItemToIcon/1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {header:HttpHeaders,status:0,statusText:"Unknown Error",url:null,ok:false,...}

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

推荐答案

请按照以下步骤操作演示:

Follow steps below for a working demo:

  1. Controller

[HttpPut("[Action]/{id}")]
public async Task<ActionResult> LinkItemToIcon(int id, IFormFile file)
{
    //your operation
}

  • Angular

    selectedFile : File = null;
    onSelectedFile(e){
        this.selectedFile = e.target.files[0];
    }
    linkItem(){
        var formData = new FormData();
        formData.append("file", this.selectedFile, this.selectedFile.name)
        this.LinkItemToIcon(1, formData).subscribe(
        r => console.log(r),
        err => console.log(err)
        )
    }
    LinkItemToIcon(id, formData) {
        return this.http.put(`api/SampleData/LinkItemToIcon/` + id, formData);
    }
    

  • 这篇关于如何在Angular 6中上传文件时修复415不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆