Reputation: 21
I use Angular 4 and I have this code.
uploadPhoto(file: File):Promise<any> {
var formData = new FormData();
formData.append('req', file);
return this.http.post(`${this.urlApi}/uploadphoto`, formData, {
withCredentials: false,
body: formData,
})
.toPromise()
.catch(this.handleError); }
Then I debug my program on Java Spring. I have in debug panel only parametr "req", but not multipart file. I set headers "multipart/form-data" and "undefined". I set "formData.append('req', file[0]); Also, I used this code:
uploadPhoto2(file:File){
var formData = new FormData();
formData.append('file', file);
var request = new XMLHttpRequest();
request.open('POST', `${this.urlApi}/uploadphoto`);
request.send(formData);
}
I have the same results. In console of chrome I see: Content-Type:multipart/form-data; boundary=----WebKitFormBoundarycE8MNSpWUCwCDLLB
When I send data from Postman (chrome exstension) I have succesfull result. Debug in Java Debug in chrome
Upvotes: 2
Views: 2314
Reputation: 2938
This code is working very well for me :
HTML CODE:(this is for image)
<div class="form-group">
<label for="usr">Upload your new photo(Optional):</label> <input type="file" accept=".jpg,.png,.jpeg" (change)="attachFile($event)">
<br>
<img src="{{imageSrc}} | defaultPipe " height="250" weight="250" alt="Image preview..." />
</div>
ANGULAR CODE :
attachFile(event) : void {
var reader = new FileReader();
let _self = this;
reader.onload = function(e) {
_self.imageSrc = reader.result;
console.log(_self.imageSrc);
};
reader.readAsDataURL(event.target.files[0]);
}
Notes: in method you must define a local variable for this operator to use it in function. In imageSrc you have the base64 byte array of file.
Upvotes: 0