【问题标题】:Angular : How to send file as part of form data that spring boot maps to the domain class?Angular:如何将文件作为 Spring Boot 映射到域类的表单数据的一部分发送?
【发布时间】:2020-05-07 03:11:02
【问题描述】:

我有一个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>

而onClickSubmit方法是

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

但这只会在浏览器控制台中记录一个假路径,例如C:\fakepath\User.java,而不是文件本身

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

FormDomain java 类

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 (No such file or directory)。 如何将文件作为 Spring Boot 映射到域类的部分表单数据发送?

【问题讨论】:

  • 也许这可以帮助你Link
  • 所以我不能将它作为表单的一部分发送? @SameerKhan
  • 如该链接所示,您可以在调用(change)函数后将文件绑定到data.fileInput = event.target.files
  • 对于post API 还有一件事,你不能像data那样直接发送文件,你必须使用form dataExplained Here
  • @SameerKhan Spring Boot 是否将 FormData 映射到域对象,就像将表单映射到域对象一样?

标签: java html angular spring-boot


【解决方案1】:

你必须写改变方法

 <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>

在ts文件中,

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")));
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 2023-03-06
    • 2022-08-02
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多