web api code :
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;
namespace WebApplication5.Controllers
{
[RoutePrefix("api/Imageuploadservice")]
public class ImageuploadserviceController : ApiController
{
[Route("Allimages")]
[HttpGet]
public HttpResponseMessage Allimages()
{
try
{
using (Database1Entities obj = new Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.IMAGEUPLOADS.ToList());
}
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[Route("Image/{ID:int}",Name ="Image")]
[HttpGet]
public HttpResponseMessage Image(int ID)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.IMAGEUPLOADS.Find(ID));
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[Route("Save")]
[HttpPost]
public HttpResponseMessage Save()
{
try
{
using (Database1Entities obj = new Database1Entities())
{
var HttpRequest =System.Web.HttpContext.Current.Request;
var Postedfile = HttpRequest.Files["IMAGE"];
System.IO.FileInfo fi = new System.IO.FileInfo(Postedfile.FileName);
string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/" + fi.Name);
if (Postedfile.ContentLength > 0)
Postedfile.SaveAs(path);
IMAGEUPLOAD vm = new Models.IMAGEUPLOAD();
vm.ID = int.Parse(HttpRequest["ID"]);
vm.NAME = HttpRequest["NAME"];
vm.PATH = "http://localhost:2813/images/" + fi.Name;
obj.Entry(vm).State = EntityState.Added;
obj.SaveChanges();
var req = Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
req.Headers.Location=new Uri(Url.Link("Image",new {ID = vm.ID }));
return req;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[Route("Update")]
[HttpPut]
public HttpResponseMessage Update()
{
try
{
using (Database1Entities obj = new Database1Entities())
{
IMAGEUPLOAD vm = new Models.IMAGEUPLOAD();
var HttpRequest = System.Web.HttpContext.Current.Request;
var Postedfile = HttpRequest.Files["IMAGE"];
int ID = int.Parse(HttpRequest["ID"]);
vm = obj.IMAGEUPLOADS.Find(ID);
vm.NAME = HttpRequest["NAME"];
if (Postedfile!=null)
{
System.IO.FileInfo fi = new System.IO.FileInfo(Postedfile.FileName);
string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/" + fi.Name);
if (Postedfile.ContentLength > 0)
Postedfile.SaveAs(path);
vm.PATH = "http://localhost:2813/images/" + fi.Name;
}
obj.Entry(vm).State = EntityState.Modified;
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[Route("Delete/{ID:int}")]
[HttpDelete]
public HttpResponseMessage Delete(int ID)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
IMAGEUPLOAD vm = obj.IMAGEUPLOADS.Find(ID);
obj.Entry(vm).State = EntityState.Deleted;
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
}
}
Angular js view :
<form class="form-horizontal" #imageForm="ngForm">
<div class="form-group" [class.has-success]="ID.valid" [class.has-error]="ID.invalid && ID.touched">
<label class="control-label col-lg-4">ID</label>
<div class="col-lg-4">
<input type="text" class="form-control" required [(ngModel)]="IMAGE1.ID" #ID="ngModel" name="ID"/>
</div>
<span class="help-block" *ngIf="ID.invalid && ID.touched">
ID should not be blank.
</span>
</div>
<div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
<label class="control-label col-lg-4">NAME</label>
<div class="col-lg-4">
<input type="text" class="form-control" required [(ngModel)]="IMAGE1.NAME" #NAME="ngModel" name="NAME"/>
</div>
<span class="help-block" *ngIf="NAME.invalid && NAME.touched">
Name should not be blank.
</span>
</div>
<div class="form-group" >
<label class="control-label col-lg-4">IMAGE</label>
<div class="col-lg-4">
<img style="height:50px;width:50px" [src]="imagepath" >
<input (change)="fillimage($event.target.files)" type="file" class="form-control" [(ngModel)]="IMAGE1.IMAGE" #IMAGE="ngModel" name="IMAGE"/>
</div>
</div>
<div class="form-group" >
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" class="btn btn-primary" value="Save" style="width:80px" (click)="save()" />
<input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update()" />
<input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset(imageForm)" />
</div>
</div>
<div class="form-group" >
<label class="control-label col-lg-4"></label>
<div class="col-lg-8">
<table class="table table-bordered table-condensed table-hover table-responsive table-striped">
<thead class="bg bg-primary">
<tr>
<th>Sl No.</th>
<th>Name</th>
<th>Image</th>
<th>Download</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of list;let i=index">
<td>{{i+1}}</td>
<td>{{c.NAME}}</td>
<td><img [src]='c.PATH' style="width:50px; height:50px" /></td>
<td><a [href]='c.PATH' download>Download</a></td>
<td>
<a (click)="edit(c.ID)">Edit</a> |
<a (click)="del(c.ID)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
Angular js Componet :
import { Component, OnInit, ViewChild } from '@angular/core';
import { Iimage } from './image.model';
import { ImageService } from './image.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-createimage',
templateUrl: './createimage.component.html',
styleUrls: ['./createimage.component.css']
})
export class CreateimageComponent implements OnInit {
IMAGE1: Iimage;
list: Iimage[];
imagepath: string;
@ViewChild('imageForm') public imForm: NgForm;
constructor(private ps: ImageService) { }
ngOnInit() {
this.CLR();
this.fill();
this.imagepath = '';
}
fillimage(im: FileList): void {
this.IMAGE1.IMAGE = im.item(0);
const reader = new FileReader();
reader.onload = (event: any) => {
this.imagepath = event.target.result;
};
reader.readAsDataURL(this.IMAGE1.IMAGE);
}
save(): void {
this.ps.Save(this.IMAGE1).then(data => {
alert(data);
this.CLR();
this.fill();
this.imagepath = null;
});
}
update(): void {
this.ps.Update(this.IMAGE1).then(data => {
alert(data);
this.CLR();
this.fill();
this.imagepath = null;
});
}
fill(): void {
this.ps.Gets().then(data => this.list = data );
}
edit(id: number): void {
this.ps.Get(id).then(data => {
this.IMAGE1.ID = data.ID;
this.IMAGE1.NAME = data.NAME;
this.imagepath = data.PATH;
});
}
del(id: number): void {
if (confirm('Do you want to delte it ?')) {
this.ps.Delete(id).then(data => {
alert(data);
this.fill();
});
}
}
reset(im: NgForm): void {
im.reset();
this.imagepath = null;
}
CLR(): void {
this.IMAGE1 = {
ID: null,
NAME: null,
IMAGE: null
};
this.imForm.reset();
}
}
Angularjs Services :
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Iimage, Iimage2 } from './image.model';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ImageService {
constructor(private http: HttpClient) { }
baseUrl = 'http://localhost:2813/api/Imageuploadservice';
Gets(): Promise<Iimage[]> {
return this.http.get<Iimage[]>(`${this.baseUrl}/${'Allimages'}`)
.toPromise();
}
Get(id: number): Promise<Iimage2> {
return this.http.get<Iimage2>(`${this.baseUrl}/${'Image'}/${id}`)
.toPromise();
}
Save(im: Iimage): Promise<string> {
const formData: FormData = new FormData();
formData.append('ID', im.ID.toString());
formData.append('NAME', im.NAME);
formData.append('IMAGE', im.IMAGE, im.IMAGE.name);
return this.http.post<string>(`${this.baseUrl}/${'Save'}`
, formData
).toPromise();
}
Update(im: Iimage): Promise<string> {
const formData: FormData = new FormData();
formData.append('ID', im.ID.toString());
formData.append('NAME', im.NAME);
if (im.IMAGE != null) {
formData.append('IMAGE', im.IMAGE, im.IMAGE.name);
}
return this.http.put<string>(`${this.baseUrl}/${'Update'}`
, formData
).toPromise();
}
Delete(id: number): Promise<string> {
return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${id}`)
.toPromise();
}
}
Angular js Model :
export interface Iimage {
ID: number;
NAME: string;
IMAGE: File;
}
export interface Iimage2 {
ID: number;
NAME: string;
PATH: string;
}
No comments:
Post a Comment