[英]How to pass the list of integers as json data to spring boot rest API?
[英]How to Pass Data from Angular 10 form to Spring Boot Rest API that includes both Strings and Files/Images?
嘗試在 Angular 10 和 Spring-Boot rest Api 之間進行通信時,我在 Eclipse 控制台中收到以下錯誤。
2020-10-06 23:44:12.261 WARN 33762 --- [nio-8090-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 535] (through reference chain: com.P.models.PModels["pProfilePic"])]
這是我的 Angular Form 的一部分
<form class="" action="" method="POST" enctype = "multipart/form-data" role="form" [formGroup]="form" (ngSubmit)="onSubmit()">
<input id="name" class="form-control" type="text" placeholder="Your Name" formControlName="pName"
class="form-control" [ngClass]="{ 'is-invalid': submitted && f.pName.errors }">
<div *ngIf="submitted || f.pName.invalid && (f.pName.dirty || f.pName.touched)"
class="alert alert-danger">
<div *ngIf="f.pName.errors?.required">Name is required</div>
</div>
<div class="form-group row mb-4">
<label for="uploadPhoto" class="col-md-3 col-form-label">Upload Photo </label>
<div class="col-md-8">
<input type="text" class="form-control mb-2 transparent-disabled" id="uploadPhoto"
placeholder="JPEG size 200kb max" [value]="filePhotoInfo" disabled>
<div *ngIf="submitted || f.pProfilePhoto.invalid && (f.pProfilePhoto.dirty || f.pProfilePhoto.touched)"
class="alert alert-danger">
<div *ngIf="f.pProfilePhoto.errors?.required"> Upload JPEG file and it should not exceed 200kb</div>
</div>
<button type="button" class="btn btn-outline-primary btn-upload"><i class="fas fa fa-cloud-upload"></i>
Upload File
<input
formControlName="pProfilePhoto"
type="file"
(change)="onPhotoSelect($event)"
class="form-control"
>
</button>
</div>
</div>
這是我的注冊 ts 文件的一部分
import { Component, OnInit } from '@angular/core';
import { NgbModalConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ValidationService } from 'src/app/Services/validation.service';
import { PRegistrationService } from 'src/app/Services/P-Services/p-registration.service';
@Component({
selector: 'app-p-registration',
templateUrl: './p-registration.component.html',
styleUrls: ['./p-registration.component.css', '../../../app.component.css'],
providers: [NgbModalConfig, NgbModal]
})
export class PRegistrationComponent implements OnInit {
checkbox1 = false;
form: any;
loading = false;
submitted = false;
public fileData = {};
constructor(
private PRegistrationService : PRegistrationService,
config: NgbModalConfig,
private modalService: NgbModal,
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private customValidator: ValidationService,
) {
// customize default values of modals used by this component tree
config.backdrop = 'static';
config.keyboard = false;
}
ngOnInit() {
this.form = this.formBuilder.group({
pName: ['', Validators.required],
pProfilePhoto: ['', Validators.required],
pProfilePic: new FormControl(''),
});
}
// convenience getter for easy access to form fields
get f() { return this.form.controls; }
// tslint:disable-next-line: typedef
onSubmit() {
this.submitted = true;
if (this.form.valid) {
const formData = new FormData();
formData.append('pProfilePic', this.form.get('pProfilePic').value);
this.PRegistrationService.pRegistration(this.form.value)
.subscribe(result => {
this.router.navigate(['PRegistration']);
}, (err) => {
console.log(err);
});
}
}
// tslint:disable-next-line: typedef
reset(){
this.form.reset();
}
// tslint:disable-next-line: typedef
open(content) {
this.modalService.open(content, { centered: true });
}
filePhotoInfo: string ='';
onPhotoSelect(event) {
if (event.target.files.length > 0) {
const pProfilePhoto = event.target.files[0];
console.log('this is ')
console.log(pProfilePhoto);
this.filePhotoInfo = `${pProfilePhoto.name}`;
this.form.patchValue({
pProfilePic: pProfilePhoto
});
}
}
}
這是我的服務 ts 文件的一部分
export class PRegistration {
public pId: number;
public pName: string;
public pProfilePic: File;
constructor(
pId: number,
pName: string,
pProfilePic: File)
{
this.pId = pId;
this.pName = pName;
this.pProfilePic = pProfilePic;
}
}
這是我的服務文件的一部分
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {HttpClient,HttpHeaders} from "@angular/common/http";
import { environment } from 'src/environments/environment';
import { PRegistration } from 'src/app/Services/P-Services/p-registration';
@Injectable({
providedIn: 'root'
})
export class PRegistrationService {
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
pRegistration(p):Observable<any>{
return this.http.post<PRegistration>(environment.api_url+"save_user",p,this.httpOptions)
}
}
這是我模型的一部分
@Entity
@Table(name = "prepository")
public class PModels {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int pId;
@Column(nullable = false)
private String pName;
private String pProfilePic;
// Constructor, getter and setter, toString
這是我服務的一部分
public void saveUser(String pName,MultipartFile pProfilePic) {
try {
String pProfilePic_file = pProfilePic.getOriginalFilename();
InputStream pProfilePic_is = pProfilePic.getInputStream();
String pProfilePic_ts = String.valueOf(System.currentTimeMillis());
try { Thread.sleep(1);} catch (InterruptedException e) { e.printStackTrace();}
String rand = UUID.randomUUID().toString();
String pProfilePic_name = pProfilePic_ts+rand+pProfilePic_file;
PModels p = new PModels();
p.setpName(pName);
p.setpProfilePic(pProfilePic_name);
pDao.save(p);
String folder = "//Users//Desktop//p//";
Path path = Paths.get(folder);
if (!Files.exists(path)) {
try {
Files.createDirectory(path);
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Directory created");
}
else {
System.out.println("Directory already exists");
}
folder = folder + p.getPId() + "//";
Path path1 = Paths.get(folder);
if (!Files.exists(path1)) {
try {
Files.createDirectory(path1);
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Directory created");
}
else {
System.out.println("Directory already exists");
}
Files.copy(pProfilePic_is,Paths.get(folder+pProfilePic_name),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
這是我的控制器的一部分
@PostMapping("/save_user")
public void saveUser(@RequestBody PModels pModels) {
this.pInfo.saveUser(pModels);
System.out.println(pModels.getpName()); // Just for checking
在您的情況下,Spring 框架假定傳入數據被編碼為 application/json,但它確實被編碼為 multiparty/form-data。 首先,您需要設置@PostMapping 注解的'consumes' 屬性。 然后您需要使用@RequestPart 批注而不是@RequestBody 批注。
我認為這篇博文展示了如何做到這一點。
如果我可以添加另一個提示:通常,使用相同的 POJO(類)來表示 Web 服務的 DB 實體和 DTO 並不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.