簡體   English   中英

上傳文件時出現錯誤 415 不支持的媒體類型

[英]Error 415 Unsupported Media Type in uploading files

我知道已經有一個類似的問題,但它沒有解決上述錯誤。

這是我在 API 的 Controller 中的 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 web 頁面中的代碼:

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但不幸的是,同樣的錯誤。 如果我在媒體類型中沒有任何類型的設置,我該如何解決這個問題?

您的代碼與前面的答案幾乎得到了它。 我寧願不更改 controller 中的參數,但有一些東西要添加,即FromForm屬性。 所以這將是你的新 controller:

[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 (如此處評論中所述)是因為服務中的formdata根據您所遵循的先前答案,正在發送JSONify formdata而不是FormData本身。

這是我在 ASP.Net Core 和 Angular 中上傳文件的方法

在 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; }
}

在我的 controller 我使用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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM