【问题标题】:Send image with difference data type from angular 7 to Rest API in spring boot 2.0.5在spring boot 2.0.5中将具有不同数据类型的图像从角度7发送到Rest API
【发布时间】:2019-11-08 20:31:20
【问题描述】:

我在“堆栈溢出”和其他网站上搜索了很多,没有答案解决我的问题。

Angular html 文件:

<form (ngSubmit)="submit">
  <div>
    <input type="file" [(ngModel)]="data.image" name="image" (change)="onFileSelected($event)">
  </div>

  <div class="form">
    <mat-form-field>
      <input matInput [(ngModel)]="data.clientName" name="clientName">
    </mat-form-field>
  </div>
  //........ Other inputs fields here//
</form>  

角度 ts 文件:

public confirmAdd(): void {
  const payload: FormData = new FormData();
  payload.append('clientName', this.data.clientName);
  payload.append('dateOfBirth', this.data.dateOfBirth.toString());
  payload.append('mobileNumber', this.data.mobileNumber);
  payload.append('email', this.data.email);
  //...............other fields here ..........//
  payload.append('image', this.selectedFile); == > the image
}    

Angular 服务 ts 文件:

private httpHeaders = new HttpHeaders({
  'Content- Type': 'multipart/form-data'
});

this.http.post(this.urlEndTestImage, payload {
  headers: this.httpHeaders
}).subscribe(res => {
  console.log(res)
});   

spring boot Rest API:

@CrossOrigin(origins = {
  "http://localhost:4200"
})
@RestController
@RequestMapping("/apiHorsesClub")

public class ClienteRestController {

  @PostMapping("/upload")
  public String uploadMultipartFile(@RequestParam("model") String clientNew, @RequestParam(value = "image") MultipartFile image) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      clientEntity client = mapper.readValue(clientNew, clientEntity.class);
      client.setImage(image.getBytes());
      clientService.save(client);
      return "successfully -> filename=" + image.getOriginalFilename();
    } catch (Exception e) {
      return "FAIL!file's size > 500KB";
    }
  }
}    

我正在尝试添加更多 @RequestParam() 并且我正在尝试 @RequestPart() 具有相同的字段名称但不起作用。

这个邮递员请求帖子的图片:

【问题讨论】:

  • 在您的代码中看不到任何问题。其实你的问题是什么?
  • Angular 无法通过 post 方法发送数据
  • 哦,我没看到。看我的回答
  • 试试这个payload.append('model', this.data); 而不是传递单独的属性。所以删除clientName、dateOfBirth、mobileNumber和email。

标签: java angular spring-boot spring-data-jpa multipartform-data


【解决方案1】:

我解决了我的问题,正如你所说的@Sudarshana,我在角度方面与“模型”不匹配,经过大量搜索后,我找到了两种发送带有差异数据的文件的方法:

  1. 通过(数据 JSON,文件)发送

    Angular html:

    <form   [formGroup]="profileForm" (ngSubmit)="onSubmit()">
     <input type="hidden" name="size" value="1000000">
     <div>
        <input type="file" (change)="onFileSelected($event)">
     </div>
     <div>
       <input type="text" formControlName="clientName" placeholder="client Name">
       <input type="text" formControlName="lastName" placeholder="Last Name">
       <input type="text" formControlName="age"  placeholder="Age">
       <button type="submit" name="upload">POST</button>
     </div>
    </form>
    

    角度测试:

    profileForm = new FormGroup({
    clientName : new FormControl(''),
    lastName : new FormControl(''),
    age : new FormControl('')
    });
    
    selectedFile = null;
    public data:clientClass = new clientClass();
    
    onFileSelected(event) {
    this.selectedFile = event.target.files[0];
    console.log(this.selectedFile);
    }
    
    onSubmit() {
    let object = this.profileForm.value;
    const payload = new FormData();
    payload.append("addClient",JSON.stringify(object));
    payload.append("image", this.selectedFile, this.selectedFile.name);
    this.http.post(`http://localhost:8080/yourAPI/uploadTestEntity`,payload, { 
    responseType: 'text'}).subscribe(
      (object) => {
        this.profileForm.reset();
      });
    }
    

    应用模块文件:

    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    @NgModule({
    imports:[ BrowserModule, FormsModule,ReactiveFormsModule ]
    })
    

    Rest API:

    @PostMapping("/uploadTestEntity")
    public String uploadTestEntity(
    @RequestParam("addClient") String clientNameEntityNew,    
    @RequestParam(value = "image") MultipartFile image) {
      try {
          ObjectMapper mapper = new ObjectMapper();
          testEntity testEntity = mapper.readValue(clientNameEntityNew,testEntity.class);
          testEntity.setImage(image.getBytes());
          TestEntityService.save(testEntity);
        return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
          } catch (  Exception e) {
      return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
    }    
    }
    

    2- 将文件和数据作为参数发送并在 Rest API 中作为参数接收:

    Angular html:

    <form (ngSubmit)="onSubmit()">
     <input type="hidden" name="size" value="1000000">
     <div>
       <input type="file" name="image" (change)="onFileSelected($event)">
     </div>
    <div>
    <input id="textauthor" [(ngModel)]="clientName" name="clientName" placeholder="Name">
    <input id="textauthor" [(ngModel)]="lastName" name="lastName" placeholder="last 
    Name">
    <input id="textauthor" [(ngModel)]="age" name="age" placeholder="age">
    <button type="submit" name="upload">POST</button>
    </div>
    </form>
    

    角度测试:

    clientName:string;
    lastName:string;
    age:string;
    resData: any;
    selectedFile = null;
    
    onFileSelected(event) {
    this.selectedFile = event.target.files[0];
    console.log(this.selectedFile);
    
    onSubmit() {
    const payload = new FormData();
    payload.append('clientName', this.clientName);
    payload.append('lastName', this.lastName);
    payload.append('age', this.age);
    payload.append('image', this.selectedFile, this.selectedFile.name);
    
    this.http.post(`http://localhost:8080/apiHorsesClub/uploadTestEntity`,
    payload).subscribe((data: any) => { this.resData = data;console.log(this.resData);
      });
    }
    

    Rest API:

    @PostMapping("/uploadTestEntity")
    public String uploadTestEntity(
             @RequestParam("clientName") String clientName ,
             @RequestParam("lastName") String lastName
             @RequestParam("age") String age
            ,@RequestParam(value = "image") MultipartFile image) {
      try {
    
          testEntity testEntity = new testEntity();
          testEntity.setImage(image.getBytes());
          testEntity.setClientName(clientName);
          testEntity.setLastName(lastName);
          testEntity.setAge(age);
        return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
    } catch (  Exception e) {
      return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
    }    
    }
    

【讨论】:

    【解决方案2】:

    您在 Service 中错过了 ,。

       private httpHeaders = new HttpHeaders({'Content- Type':'multipart/form-data'});
           this.http.post(this.urlEndTestImage, payload, { headers:this.httpHeaders })
           .subscribe(
               res => {  console.log(res) } );
    

    【讨论】:

    • 不工作,我将在 Eclipse 中发送错误图像,如何发送字段名称的问题
    • 其实我对 Sprint-boot 并不熟悉。但是您以FormData 发送数据,这意味着在HTTP POST 正文中。您无法使用RequestParam 捕获它。并且您的后端 API 需要一个参数作为模型,但您不是从角度发送它。见下文。你会有一些想法stackoverflow.com/questions/22163397/…
    • 上传数据文件的问题
    • 使用邮递员检查您的后端是否按您的需要工作
    • 您在FormData 中发送model 字段吗?您添加的图像中的 bcoz 错误与模型属性有关
    猜你喜欢
    • 2019-06-24
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2020-11-26
    • 2019-09-07
    • 2020-06-22
    • 2019-09-23
    相关资源
    最近更新 更多