Actually, I\'m working on a Spring REST API with an interface coded in Angular 2.
My problem is I can\'t upload a file with Angular 2.
My Webresources in jav
This has worked for me:
<input type="file" (change)="onChange($event)" required class="form-control " name="attach_file" id="attach_file">
onChange(event: any) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('degree_attachment', file, file.name);
let headers = new Headers();
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post('http://url', formData,options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}}
fileUpload() {
const formData = new FormData();
const files = this.filesToUpload;
for (let i = 0; i < files.length; i++) {
formData.append('file', files.item(i));
formData.append('Content-Type', 'application/json');
formData.append('Accept', `application/json`);
}
this.http.post('http://localhost:8080/UploadFile', formData).subscribe(response => console.log(response));
}
Then:
<form (ngSubmit)="upload()">
<input type="file" id="file" multiple (change)="fileUpload($event.target.files)">
<button type="submit">Upload</button>
</form>
This has worked for me: Angular 2 provides good support to upload file:
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(URL, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
I was getting error : java.io.IOException: RESTEASY007550: Unable to get boundary for multipart
In order to solve this you should remove the "Content-Type" "multipart/form-data"