我正在try 将角形数据上传到Spring Boot服务器.

简单地说,在《春靴》中我接受:

data class Photo(
    val id: Long = 0L,
    val file: MultipartFile
)

data class PostRequest(
    @field:Size(min = 1, max = 100)
    val title: String,

    val photos: List<Photo> = mutableListOf()
)

通过控制器:

fun createPost(@Valid @ModelAttribute postRequest: PostRequest)

在Angular 上,我创建了这个形状:

this.postForm = this.fb.group({
   title: ["", [Validators.required, Validators.minLength(1)]],
   photos: this.fb.array([]),
});

当用户上传照片时,我将这些线路称为:

const photosArray = this.postForm.get("photos") as FormArray;
          
const newPhotoGroup = this.fb.group({
  id: "",
  file: event.target.result,
});
          
photosArray.push(newPhotoGroup);

最后,我构造了一个表单数据对象:

const formData = new FormData();
formData.append("title", this.postForm.get("title")?.value);
formData.append("photos", this.postForm.get("photos")?.value);

我使用此函数将此表单发布到API:

 postRequest<T>(url: string, body: any): Observable<HttpResponse<T>> {
    const headers = new HttpHeaders({
      "Content-Type": "multipart/form-data",
    });

    return this.http.post<T>(url, body, {
      headers,
      observe: "response",
      withCredentials: true,
    });
  }

在开发人员工具中,我看到以下请求:

enter image description here

Spring Boot抱怨道:

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

谁来给我开导一下.谢谢.

推荐答案

photos表单控件是一个对象数组,在请求中像这样(作为[object Object])发送,因此出现错误.

您需要循环数组并追加每个文件:

const formData = new FormData();
formData.append("title", this.postForm.get("title")?.value);
// loop files and append them
this.postForm.get("photos")?.value.forEach((obj:any, i:number)=>{
    formData.append("photos", obj.file); // user property which has file:File
});

此外,在将文件添加到数组时,请确保它的类型为File(event.target.result现在似乎是一个字符串,如果是,请使用event.target.file或添加一个新属性,例如‘ploadFile’,然后将其添加到formData):

const newPhotoGroup = this.fb.group({
    id: "",
    file: event.target.result, // this should be File from event.target.file
  });

if you want to include 100, i.e. custom file data, along with the file, it cannot go along with the file in the same formData key

您可以使用id而不是文件名:

formData.append("photos", obj.file, obj.id)

或者对上传过程进行如下修改:sending JSON object along with file using FormData in ajax call and accessing the json object in PHP


最后,在没有content-type headers的情况下进行请求,FormData将处理它:

return this.http.post<T>(url, body, {
    observe: "response",
    withCredentials: true,
  });

Typescript相关问答推荐

返回对象的TypScript构造函数隐式地替换This的值来替换super(.)的任何调用者?

即使子网是公共的,AWS CDK EventBridge ECS任务也无法分配公共IP地址

APP_INITIALIZER—TypeError:appInits不是函数

类型脚本类型字段组合

泛型类型,引用其具有不同类型的属性之一

在映射类型中用作索引时,TypeScrip泛型类型参数无法正常工作

在类型脚本中的泛型类上扩展的可选参数

在另一个类型的函数中,编译器不会推断模板文字类型

推断从其他类型派生的类型

按函数名的类型安全类型脚本方法包装帮助器

从泛型类型引用推断的文本类型

正交摄影机正在将渲染的场景切成两半

为什么&Quot;元素隐式具有';Any';类型,因为...即使我已经打字了,也不能作为索引显示错误吗?

为什么上下文类型在`fn|curred(Fn)`的联合中不起作用?

在正常函数内部调用异步函数

将超类型断言为类型脚本中的泛型参数

如何在本地存储中声明该类型?

编剧- Select 下拉框

是否可以将类型参数约束为不具有属性?

在Nestjs中,向模块提供抽象类无法正常工作