gpt4 book ai didi

angular - 使用 Angular 2 和 Spring MVC 中的其他表单字段上传文件

转载 作者:太空狗 更新时间:2023-10-29 17:43:54 24 4
gpt4 key购买 nike

我正在尝试从我的 Angular 2 前端上传文件和其他表单字段内容到 Spring 后端。但不知何故我做不到。这是我的代码:

app.component.ts

fileChange(e){
this.fileList = e.target.files;
}

uploadPdf(){
if(this.fileList.length>0){
let file: File = this.fileList[0];
let formData:FormData = new FormData();

formData.append('uploadFile', file, file.name);
formData.append('info',this.model);

console.log(file.size);

let headers = new Headers();
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(this.url,formData, options)
/*.map((res: Response) => res.json())*/
.catch(error => Observable.throw(error))
.subscribe(
data =>{
this.data = data;
console.log(this.data);
}
,
error => console.log(error)
)
}
}

app.cmoponent.html

<h1 class="text-center">
PDF Viewer and Uploader Example
</h1>
<div class="text-center">
<form enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name: </label>
<input type="text" id="name" class="form-control" name="name" [(ngModel)]="model.name">
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" class="form-control" name="email" [(ngModel)]="model.email">
</div>
<div class="form-group">
<label for="pdfInput">Select File: </label>
<input type="file" id="pdfInput" class="form-control" name="pdfInput" (change)="fileChange($event)">
</div>
<div class="form-group">
<button type="button" class="btn btn-success" (click)="uploadPdf()">Upload File!</button><span> </span>
<button type="button" class="btn btn-success" (click)="printData()">Print to Console!</button>
</div>
</form>
</div>

模型.ts

export class Model{

name: string;
email: string;

}

现在在后端:

ExampleModel.java

public class ExampleModel {

private String name;
private String email;
//Getters and Setters

主 Controller .java

@RequestMapping(value = "/file",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> addUser(@RequestParam("uploadFile") MultipartFile file, @RequestParam("info") ExampleModel model){}

那么,如何在 spring controller 中获取 info 标记的数据呢?上面我已经展示了我的尝试是错误的,那么获取其他表单字段数据的正确方法是什么?

应该如何定义带有注释的 Controller 方法,或者是否有其他方式从 Angular 2 发送数据(文件 + 表单字段)?

最佳答案

您需要使用 @RequestPart 而不是 @RequestParam 并设置 consumes 属性:

@RequestMapping(value = "/file",method = RequestMethod.POST, consumes = "multipart/form-data")
@ResponseBody
public ResponseEntity<String> addUser(@RequestPart("uploadFile") MultipartFile file, @RequestPart("info") ExampleModel model){}

您还需要调整您的 FormData 对象:

formData.append('uploadFile', file, file.name);
formData.append('info', new Blob([JSON.stringify(this.model)],
{
type: "application/json"
}));

关于angular - 使用 Angular 2 和 Spring MVC 中的其他表单字段上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43064548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com