Java Angular:如何将文件作为spring引导映射到域类的表单数据的一部分发送?

Java Angular:如何将文件作为spring引导映射到域类的表单数据的一部分发送?,java,html,angular,spring-boot,Java,Html,Angular,Spring Boot,我有一个html表单,如下所示 <form #basicForm = "ngForm" (ngSubmit) = "onClickSubmit(basicForm.value)" enctype="multipart/form-data" class="form-horizontal"> <input type="file" id="file-input" name="fileInput" ngModel> <button type="subm

我有一个html表单,如下所示

 <form #basicForm = "ngForm" (ngSubmit) = "onClickSubmit(basicForm.value)" enctype="multipart/form-data" class="form-horizontal">
     <input type="file" id="file-input" name="fileInput" ngModel>
     <button type="submit"> Submit</button>
 </form>
但这只会在浏览器控制台中记录一个伪路径,比如
C:\fakepath\User.java
而不是文件本身

我无法从服务器端访问文件,似乎只有伪路径被上传到服务器,而不是文件本身

FormDomainJava类

public class FormDomain {
 private File fileInput;

public File getFileInput() {
    return fileInput;
}

public void setFileInput(File fileInput) {
    this.fileInput = fileInput;
}

}
窗体控制器

@CrossOrigin(origins="*")
@RestController
public class FormController {
      @PostMapping(path="/basicForm")
 public String postResponseController(
              @RequestBody FormDomain loginForm) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(loginForm.getFileInput())); 

          String st; 
          while ((st = br.readLine()) != null) { 
            System.out.println(st); 
          } 

         return "file transfer completed successfully";
     }
}
以这种方式访问上载的文件会导致错误
java.io.FileNotFoundException:C:\fakepath\User.java(没有这样的文件或目录)

如何将文件作为spring boot映射到域类的表单数据的一部分发送?

您必须编写更改方法

 <form #basicForm = "ngForm" (ngSubmit) = "onClickSubmit(basicForm.value)" enctype="multipart/form-data" class="form-horizontal">
     <input type="file" id="file-input" name="fileInput" (change)="onFileChange($event)" ngModel>
     <button type="submit"> Submit</button>
 </form>
发送到后端时

onClickSubmit(data) {
    data.fileInput = this.selectedFile ;
    console.log(data.fileInput);
    this.http.post("http://localhost:8080/basicForm", data).subscribe( (ob)=>(console.log("subscribe method called")));
  }

也许这可以帮助你,所以我不能把它作为表格的一部分发送@该链接中显示的SameerKhanas在调用
(更改)
函数后,您可以将文件绑定到
data.fileInput=event.target.files
,对于
post
API,您不能像发送数据一样直接发送文件,您必须使用
表单数据
@SameerKhan spring boot是否将表单数据映射到域对象,就像它将表单映射到域对象一样?
selectedFile : any = null;
onFileChange(event){
 if (event.target.files && event.target.files.length) {
  this.pdfFile = event.target.files[0];
 }
}
onClickSubmit(data) {
    data.fileInput = this.selectedFile ;
    console.log(data.fileInput);
    this.http.post("http://localhost:8080/basicForm", data).subscribe( (ob)=>(console.log("subscribe method called")));
  }