使用 Angular 2 和 Spring MVC 中的其他表单字段上传文件 [英] Uploading file with other form fields in Angular 2 and Spring MVC

查看:27
本文介绍了使用 Angular 2 和 Spring MVC 中的其他表单字段上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

app.component.ts

fileChange(e){this.fileList = e.target.files;}上传PDF(){如果(this.fileList.length>0){让文件:文件 = this.fileList[0];让 formData:FormData = new FormData();formData.append('uploadFile', file, file.name);formData.append('info',this.model);控制台日志(文件大小);让标题=新标题();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)).订阅(数据 =>{this.data = 数据;控制台日志(this.data);},错误 =>控制台日志(错误))}}

app.cmoponent.html

PDF 查看器和上传器示例

<div class="text-center"><form enctype="multipart/form-data"><div class="form-group"><label for="name">名称:</label><input type="text" id="name" class="form-control" name="name" [(ngModel)]="model.name">

<div class="form-group"><label for="email">电子邮件:</label><input type="email" id="email" class="form-control" name="email" [(ngModel)]="model.email">

<div class="form-group"><label for="pdfInput">选择文件:</label><input type="file" id="pdfInput" class="form-control" name="pdfInput" (change)="fileChange($event)">

<div class="form-group"><button type="button" class="btn btn-success" (click)="uploadPdf()">上传文件!</button><span></span><button type="button" class="btn btn-success" (click)="printData()">打印到控制台!</button>

</表单>

model.ts

导出类模型{名称:字符串;电子邮件:字符串;}

现在在后端:

ExampleModel.java

公共类 ExampleModel {私人字符串名称;私人字符串电子邮件;//获取器和设置器

MainController.java

@RequestMapping(value = "/file",method = RequestMethod.POST)@ResponseBody公共响应实体addUser(@RequestParam("uploadFile") MultipartFile 文件,@RequestParam("info") ExampleModel 模型){}

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

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

解决方案

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

@RequestMapping(value = "/file",method = RequestMethod.POST,consumes = "multipart/form-data")@ResponseBody公共响应实体addUser(@RequestPart("uploadFile") MultipartFile 文件,@RequestPart("info") ExampleModel 模型){}

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

formData.append('uploadFile', file, file.name);formData.append('info', new Blob([JSON.stringify(this.model)],{类型:应用程序/json"}));

I am trying to upload file and other form field contents from my Angular 2 front end to Spring back end. But somehow I am not able to do it. Here is my code:

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>

model.ts

export class Model{

  name: string;
  email: string;

}

Now in Backend:

ExampleModel.java

public class ExampleModel {

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

MainController.java

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

So, how to get that info labeled data in the spring controller? Above I have shown my attempt which is wrong so, what is the correct approach to get other form fields data?

How the Controller method with annotations should be defined or is there other way to send data(both file + form fields) from Angular 2?

解决方案

You need to use @RequestPart instead of @RequestParam and set consumes attribute:

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

You also need to adjust your FormData object:

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

这篇关于使用 Angular 2 和 Spring MVC 中的其他表单字段上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆