java - 在 spring boot 2.0.5 中将具有不同数据类型的图像从 Angular 7 发送到 Rest API

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

我在“stack overflow”和其他网站上搜索了很多,没有答案可以解决我的问题。

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>  

Angular 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()。

这张 postman 请求邮寄的图片:

it's work no problem and save the image with data to mySql

最佳答案

您在服务中遗漏了,

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

关于java - 在 spring boot 2.0.5 中将具有不同数据类型的图像从 Angular 7 发送到 Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780524/

相关文章:

java - 在Amazon Web Services上部署Java Web应用程序

java - 单个表的两个版本的 JPA 实体

docker - 如何在没有 JAR 的情况下为 Spring Boot 应用程序构建 Docker 镜像

java - OutOfMemoryError - 如何在 hprof 创建后终止 JVM

java - ChangeListener 在 Javafx 中未触发

angular - 应该显示在表格中的嵌套循环

Angular 2 : get elementref on child component from parent

angular - 使用 ng-container 在 *ngIf 中嵌套条件

spring-boot - Spring Boot WAR部署到tomcat

java - 具有不同 url 但具有相同参数和相同方法功能的请求映射