Reputation: 633
I have a basic question. It is possible to send two parameter form POST method in Angular and Java Spring. One parameter is JSON object second is an image.
I have a simple example in Angular to explain what I want:
addHero(file: File,category: CategoryModel): Observable<any> {
const formdata: FormData = new FormData();
formdata.append('file', file);
return this.http.post<File>(this.cateogryUrl, {formdata,category} )
.pipe(
// catchError(this.handleError('addHero', file))
);
}
Upvotes: 1
Views: 4691
Reputation: 410
Hello there you need to follow these steps.
Convert File in to base 64 as
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
getBase64(file).then(base64=>{
var base64 = base64;
});
Now you have to send the base64 with the formdata as
formdata.append('base64', base64); // base64 from the method
Now get the base64 at JAVA and convert it in File at JAVA end.
Thank you :) any query please comment down and thumbs up if you get your thing
Upvotes: 1
Reputation: 365
It depends on your backend. If it takes image as a multipartfile, you can't send json data with it. But you can append other values which is desired to the form data. If it takes image as a base64 file, you can use json object to send data.
Upvotes: 1
Reputation: 1537
You can always convert it to BASE64. Then it's a simple string which you can simply pass it within the JSON (or a different one).
EDIT
This is what i do in my case any time a user upload a file. Isimply transform the file chosen to a BASE64 string. There are some really nice resources out there about this.
onFileChanged(event) {
const file = event.target.files[0];
if (file.type.split('/')[0] !== 'image') {
this.validFile = false;
}
this.imageUploadModel.ImageType = file.type.split('/')[1];
const myReader: FileReader = new FileReader();
myReader.onloadend = (e) => {
this.imageUploadModel.Base64String = myReader.result.toString();
};
myReader.readAsDataURL(file);
}
This is my model
export class ImageUploadModel {
Title: string;
Description: string;
ImageType: string;
Base64String: string;
}
And i stringify it so i can send it on the body of the request:
const body = JSON.stringify(this.imageUploadModel);
Upvotes: 1
Reputation: 419
formdata.append('file', file);
formdata.append('key1', value1);
formdata.append('key2', value2);
You can add multiple key pair value like this.
If there too many, you can also iterate in for loop
for(let key in someObject){
formdata.append(key, someObject[key]);
}
Upvotes: 0