【问题标题】:Error 415 Unsupported Media Type in uploading files上传文件时出现错误 415 不支持的媒体类型
【发布时间】:2019-11-18 08:52:06
【问题描述】:

我知道已经有一个similar question,但是并没有解决上面的错误。

这是我在 API 控制器中的 PUT 操作,在 Swagger 中运行良好:

[HttpPut("{id}/upload")]
public async Task<IActionResult> UploadFile(string id, IFormFile file)  
{
    // codes using id above are omitted, nothing to do with the error

    var path = Path.Combine(
        Directory.GetCurrentDirectory(),
        "wwwroot",
        file.FileName
    );

    using (var stream = new FileStream(path, FileMode.Create))  
    {  
        await file.CopyToAsync(stream);
    }

    return Ok();
}

这是我的 Angular 网页中的代码:

HTML

<input type="file" (change)="setFile($event.target.files)"/>

<button (click)="save()"> Save </button>

TypeScript

forUpload: File = null;
@Input() someModel: SomeModel;

// setting of file
setFile(myFile: File){
    if (myFile === null){
      return;
    }
    this.forUpload = myFile[0];
}

// saving
save() {
    const addFileFnc = this.theService.addFile.bind(this.theService);
    addFileFnc(this.someModel, this.forUpload).subscribe(
        () => { this.ref.close(); },
        (e) => { console.log(e); }
    );
}

而且,我的服务是:

addFile(someModel: SomeModel, myFile: File): Observable<any> {
    return this.http.put(`${api_url}/api/somemodels/${someModel.id}/upload`, {
        id: someModel.id,
        file: myFile
    });
}

我还使用FormData 来尝试上述问题的答案,我将我的forUpload 文件附加到FormData 但不幸的是,同样的错误。如果我在媒体类型中没有任何类型的设置,我该如何解决这个问题?

【问题讨论】:

    标签: c# angular typescript asp.net-core rxjs


    【解决方案1】:

    您的代码和前面的答案几乎得到了它。我宁愿不更改控制器中的参数,但要添加一些内容,即FromForm 属性。所以这将是你的新控制器:

    [HttpPut("{id}/upload")]
    public async Task<IActionResult> UploadFile(string id, [FromForm] IFormFile file)  
    {
        // codes here
    }
    

    我同意之前使用FormData 的回答,但我不会对您的setFile() 进行任何更改,只是对typescript 进行一些补充:

    forUpload: File = null;
    @Input() someModel: SomeModel;
    
    save() {
    
        const addFileFnc = this.theService.addFile.bind(this.theService);
    
        const formdata = new FormData();
        formdata.append("id", this.someModel.id);
        formdata.append("file", this.forUpload);
    
        addFileFnc(formdata).subscribe(
            () => { this.ref.close(); },
            (e) => { console.log(e); }
        );
    }
    

    我没有附加整个someModel,而是只添加了您的someModel.id,因为我注意到它是您在服务中唯一使用的东西,它将被更改为:

    addFile(formdata: FormData): Observable<any> {
        return this.http.put(`${api_url}/api/somemodels/${formdata.get("id")}/upload`, formdata);
    }
    

    您的Error 400 Bad Request(正如in the comments here 所说)是因为服务 中的formdata 根据您之前关注的答案发送一个JSONify em> formdata 而不是 FormData 本身。

    【讨论】:

      【解决方案2】:

      这是我在 ASP.Net Core 和 Angular 中上传文件的方式

      在角度方面,您将需要使用 FormData 提交

      const formdata = new FormData();
      formdata.append("SomeProp ", "somestring");
      formdata.append("Image ", myFile); // change your code accordingly here
      
      return this.http.put(`${api_url}/api/somemodels/${someModel.id}/upload`, {
          formdata
      });
      

      在服务器端

      public class PostViewModel
      {
          public string SomeProp { get; set; }
          public IFormFile Image { get; set; }
      }
      

      在我的控制器中我使用FromForm 属性

      public async Task<IActionResult> SavePost([FromForm]PostViewModel viewModel)
      

      更新: 确保像这样在 ASP.Net Core 中启用 CORS 支持

      启用 CORS

      public void ConfigureServices(IServiceCollection services)
      {
            services.AddCors();
            services.AddMvc();
      }
      
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
          app.UseCors(
              options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
          );
      
          app.UseMvc();
      }
      

      【讨论】:

      • 感谢您的回复。但是在做了你的建议之后,错误仍然存​​在。这和File.type()有关系吗?
      • 你是什么意思 File.type() ?你从哪里得到的
      • 我没有在我当前的代码中使用它,但我只是好奇是否需要修改文件的 mime 类型。但是我的代码中没有任何限制任何类型的配置。
      • 我现在意识到它不是同一个错误。在错误 415 之后,它转到了与 CORS 相关的错误,然后修复。现在它当前返回错误 400。这有什么问题?
      • 是的,我已经完成了 CORS。我修复了它,但错误 400 Bad Request 替换了 CORS 错误。
      猜你喜欢
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2018-10-13
      • 2018-07-25
      • 2016-09-09
      • 2021-10-15
      相关资源
      最近更新 更多