I'm a beginner with Angular, I want to know how to create Angular 5 File upload part, I'm trying to find any tutorial or doc, but I don't see anything anywhere. Any idea for this? And I tried ng4-files but it's not working for Angular 5
HTML allows you to add the file upload functionality to your website by adding a file upload button to your webpage with the help of the <input> tag. The <input type=”file”> defines a file-select field and a “Browse“ button for file uploads.
Here is a working example for file upload to api:
Step 1: HTML Template (file-upload.component.html)
Define simple input tag of type file
. Add a function to (change)
-event for handling choosing files.
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
Step 2: Upload Handling in TypeScript (file-upload.component.ts)
Define a default variable for selected file.
fileToUpload: File | null = null;
Create function which you use in (change)
-event of your file input tag:
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
If you want to handle multifile selection, than you can iterate through this files array.
Now create file upload function by calling you file-upload.service:
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
Step 3: File-Upload Service (file-upload.service.ts)
By uploading a file via POST-method you should use FormData
, because so you can add file to http request.
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
So, This is very simple working example, which I use everyday in my work.
This way I implement upload file to web API in project.
I share for whom concern.
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
Step by step
ASP.NET Web API
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML form
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
class="material-icons">save</i></button>
</div>
</form>
TS file to use API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
Service TS
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With