I know this is very a general question but I am failing to upload a file in Angular 2. I have tried
1) http://valor-software.com/ng2-file-upload/ and
2) h
Thanks to @Eswar. This code worked perfectly for me. I want to add certain things to the solution :
I was getting error : java.io.IOException: RESTEASY007550: Unable to get boundary for multipart
In order to solve this error, you should remove the "Content-Type" "multipart/form-data". It solved my problem.
This simple solution worked for me: file-upload.component.html
<div>
<input type="file" #fileInput placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
</div>
And then do the upload in the component directly with XMLHttpRequest.
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {
@ViewChild('fileInput') fileInput;
constructor() { }
ngOnInit() {
}
private upload() {
const fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
formData.append('files', fileBrowser.files[0]);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/Data/UploadFiles', true);
xhr.onload = function () {
if (this['status'] === 200) {
const responseText = this['responseText'];
const files = JSON.parse(responseText);
//todo: emit event
} else {
//todo: error handling
}
};
xhr.send(formData);
}
}
}
If you are using dotnet core, the parameter name must match the from field name. files in this case:
[HttpPost("[action]")]
public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files)
{
return await _binaryService.UploadFilesAsync(files);
}
This answer is a plagiate of http://blog.teamtreehouse.com/uploading-files-ajax
Edit: After uploading, you have to clear the file-upload so that the user can select a new file. And instead of using XMLHttpRequest, maybe it is better to use fetch:
private addFileInput() {
const fileInputParentNative = this.fileInputParent.nativeElement;
const oldFileInput = fileInputParentNative.querySelector('input');
const newFileInput = document.createElement('input');
newFileInput.type = 'file';
newFileInput.multiple = true;
newFileInput.name = 'fileInput';
const uploadfiles = this.uploadFiles.bind(this);
newFileInput.onchange = uploadfiles;
oldFileInput.parentNode.replaceChild(newFileInput, oldFileInput);
}
private uploadFiles() {
this.onUploadStarted.emit();
const fileInputParentNative = this.fileInputParent.nativeElement;
const fileInput = fileInputParentNative.querySelector('input');
if (fileInput.files && fileInput.files.length > 0) {
const formData = new FormData();
for (let i = 0; i < fileInput.files.length; i++) {
formData.append('files', fileInput.files[i]);
}
const onUploaded = this.onUploaded;
const onError = this.onError;
const addFileInput = this.addFileInput.bind(this);
fetch('/api/Data/UploadFiles', {
credentials: 'include',
method: 'POST',
body: formData,
}).then((response: any) => {
if (response.status !== 200) {
const error = `An error occured. Status: ${response.status}`;
throw new Error(error);
}
return response.json();
}).then(files => {
onUploaded.emit(files);
addFileInput();
}).catch((error) => {
onError.emit(error);
});
}
https://github.com/yonexbat/cran/blob/master/cranangularclient/src/app/file-upload/file-upload.component.ts
Since the code sample is a bit outdated I thought I'd share a more recent approach, using Angular 4.3 and the new(er) HttpClient API, @angular/common/http
export class FileUpload {
@ViewChild('selectedFile') selectedFileEl;
uploadFile() {
let params = new HttpParams();
let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])
const options = {
headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
params: params,
reportProgress: true,
withCredentials: true,
}
this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
data => {
console.log("Subscribe data", data);
},
(err: HttpErrorResponse) => {
console.log(err.message, JSON.parse(err.error).error.message);
}
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}
Try not setting the options
parameter
this.http.post(${this.apiEndPoint}, formData)
and make sure you are not setting the globalHeaders
in your Http factory.
This is useful tutorial, how to upload file using the ng2-file-upload and WITHOUT ng2-file-upload.
For me it helps a lot.
At the moment, tutorial contains a couple of mistakes:
1- Client should have same upload url as a server,
so in app.component.ts
change line
const URL = 'http://localhost:8000/api/upload';
to
const URL = 'http://localhost:3000';
2- Server send response as 'text/html', so in app.component.ts
change
.post(URL, formData).map((res:Response) => res.json()).subscribe(
//map the success function and alert the response
(success) => {
alert(success._body);
},
(error) => alert(error))
to
.post(URL, formData)
.subscribe((success) => alert('success'), (error) => alert(error));
Today I was integrated ng2-file-upload package to my angular 6 application, It was pretty simple, Please find the below high-level code.
import the ng2-file-upload module
app.module.ts
import { FileUploadModule } from 'ng2-file-upload';
------
------
imports: [ FileUploadModule ],
------
------
Component ts file import FileUploader
app.component.ts
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
------
------
const URL = 'http://localhost:3000/fileupload/';
------
------
public uploader: FileUploader = new FileUploader({
url: URL,
disableMultipart : false,
autoUpload: true,
method: 'post',
itemAlias: 'attachment'
});
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
}
------
------
Component HTML add file tag
app.component.html
<input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
Working Online stackblitz Link: https://ng2-file-upload-example.stackblitz.io
Stackblitz Code example: https://stackblitz.com/edit/ng2-file-upload-example
Official documentation link https://valor-software.com/ng2-file-upload/