【发布时间】: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 -
对于
postAPI 还有一件事,你不能像data那样直接发送文件,你必须使用form dataExplained Here -
@SameerKhan Spring Boot 是否将 FormData 映射到域对象,就像将表单映射到域对象一样?
标签: java html angular spring-boot