将 angular 7 的不同数据类型的图像发送到 spring boot 2.0.5 中的 Rest API
Send image with difference data type from angular 7 to Rest API in spring boot 2.0.5
我在 "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 文件:
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开机休息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(
) 使用相同的字段名称但不起作用。
此图像 post人请求 post:
您在 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 我在 angular 方面不匹配 "model",经过大量搜索我发现了两种发送具有差异数据的文件的方法:
发送方式(数据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>
Angular 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:
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>
Angular 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";
}
}
我在 "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 文件:
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开机休息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(
) 使用相同的字段名称但不起作用。
此图像 post人请求 post:
您在 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 我在 angular 方面不匹配 "model",经过大量搜索我发现了两种发送具有差异数据的文件的方法:
发送方式(数据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>
Angular 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:
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>
Angular 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"; } }