[英]Send image with difference data type from angular 7 to Rest API in spring boot 2.0.5
我在“堆棧溢出”和其他站點中搜索了很多,沒有答案解決我的問題。
角度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
}
角服務 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(
) 但不起作用。
郵遞員請求帖子的這張圖片:
你錯過了,
在你的Service
。
private httpHeaders = new HttpHeaders({'Content- Type':'multipart/form-data'});
this.http.post(this.urlEndTestImage, payload, { headers:this.httpHeaders })
.subscribe(
res => { console.log(res) } );
我解決了我的問題,正如你所說的@Sudarshana,我在角度方面與“模型”不匹配,經過大量搜索,我找到了兩種發送帶有差異數據的文件的方法:
發送方式(數據 JSON,文件)
角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>
角度 ts:
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 ] })
休息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 中將文件和數據作為參數發送並作為參數接收:
角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>
角度 ts:
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); }); }
休息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"; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.