asp.net .Net 7 API不接受列表< IFormFile>

hivapdat  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(115)

我有以下方法
第一个月
这在下面被定义为POST方法:

public override void Map(WebApplication app)
 {
     app.MapGroup(this)
         //.RequireAuthorization()
         .MapGet(GetComponentsWithPagination)
         .MapGet(GetComponentInfo, "GetComponentInfo/{id}")
         .MapPost(CreateComponent)
         .MapPost(UploadComponentBook, "UploadComponentBook/{startPage}")
         .MapPost(AddImagesToComponent, "AddImages/{id}")
         .MapPut(UpdateComponent, "{id}")
         .MapPut(UpdateComponentDetail, "UpdateDetail/{id}")
         .MapDelete(DeleteComponent, "{id}");
 }

字符串
当我尝试用下面的代码从我的VueJS应用程序调用它时。我尝试发送的文件是图像。

try {
        const formData = new FormData();

        for (const file of files) {
          formData.append("files", file);
        }
        await axios.post(
          "https://localhost:5001/api/Components/AddImages/" +
            this.selectedComponent.id,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );
      } catch (error) {
        alert(error);
        console.log(error);
      }


我得到一个415不支持的媒体类型响应。我也从 Postman 那里试过这个,但我得到了同样的结果。
当我尝试这样做与一个单一的文件作为IFormFile文件它确实工作。
我已经尝试过使用IList,ICollection,IFormFileCollection,IFormFile[],但这些都不起作用。我试图将[FromForm]属性添加到方法中,但NSwag开始起作用并给出给予错误:

System.InvalidOperationException: files must have a valid TryParse method to support converting from a string. No public static bool List<IFormFile>.TryParse(string, out List<IFormFile>) method found for files.
1>   at Microsoft.AspNetCore.Http.RequestDelegateFactory.BindParameterFromValue(ParameterInfo parameter, Expression valueExpression, RequestDelegateFactoryContext factoryContext, String source)

8cdiaqws

8cdiaqws1#

试试看:

[HttpPost("AddImages")]
public async Task<IResult> AddImagesToComponent(int id, List<IFormFile> files)
{
   //do your staff
}

字符串
演示如下:

<input type="file" name="file" id="file" multiple />

  ...
try {
    const formData = new FormData();
     $.each($("input[type='file']")[0].files, function(i, file) {
        formData.append('files', file);
    });
    var id= this.selectedComponent.id;
   
    await axios.post(
      "https://localhost:5001/api/Components/AddImages/?id="+id,           
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );
  } catch (error) {
    alert(error);
    console.log(error);
  }


结果:

相关问题