Web api code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication2.Models;
using System.Web.Http.Cors;
namespace WebApplication2.Controllers
{
[RoutePrefix("api/Emp")]
[EnableCors("*","*","*")]
public class EmpController : ApiController
{
[HttpPost]
[Route("Save")]
public IHttpActionResult Save()
{
try
{
EMP emp = new EMP();
if (ModelState.IsValid)
{
using (Database1Entities obj = new Database1Entities())
{
if (HttpContext.Current.Request.Files.Count>0)
{
var file = HttpContext.Current.Request.Files["UpImage"];
if (file != null)
{
file.SaveAs(HttpContext.Current.Server.MapPath("~/Image/" + Path.GetFileName(file.FileName)));
emp.EID = Convert.ToInt32(HttpContext.Current.Request.Form["EID"]);
emp.NAME = HttpContext.Current.Request.Form["NAME"];
emp.PATH = "Image/" + Path.GetFileName(file.FileName);
obj.EMPs.Add(emp);
obj.SaveChanges();
}
}
return Created(new Uri(Url.Link("Get", new { EID = emp.EID })), "Data Saved.");
}
}
else
return BadRequest(ModelState);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("Allemps")]
public IHttpActionResult Allemps()
{
try
{
using(Database1Entities obj=new Database1Entities())
{
var data = obj.EMPs.ToList();
if (data.Count > 0)
{
return Ok(data);
}
else
return Content(HttpStatusCode.NoContent, "No Data");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("Emp/EID",Name="Get")]
public IHttpActionResult Emp(int EID)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
var data = obj.EMPs.Find(EID);
if (data!=null)
{
return Ok(data);
}
else
return Content(HttpStatusCode.NoContent, "No Data");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
view code :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
</head>
<body>
    <div>
        <input id="EID" type="text"  /><br />
        <input id="NAME" type="text" /><br />
            Select File to Upload: <input id="fileUpload" type="file" />
            <input id="btnUploadFile" type="button" value="Upload File" />
        <table id="tb" border="1" cellpadding="0" cellspacing="0">
        </table>
    </div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: "http://localhost:49260/api/Emp/Allemps",
            type: 'GET',
            success: function (data)
            {
                $.each(data, function (i, v) {
                    var p = "http://localhost:49260/" + v.PATH;
                    $('#tb').append("<tr><td>" + v.EID + "</td><td>" + v.NAME + "</td><td><img height=100 width=100 src=' " + p + "'></td></tr>");
                })
            }
        })
        $('#btnUploadFile').on('click', function () {
            var data = new FormData();
            var files = $("#fileUpload").get(0).files;
            if (files.length > 0) {
                data.append("UpImage", files[0]);
                data.append("EID", $('#EID').val());
                data.append("NAME", $('#NAME').val());
            }
            var ajaxRequest = $.ajax({
                type: "POST",
                url: "http://localhost:49260/api/Emp/Save",
                contentType: false,
                processData: false,
                data: data,
                success: function (data)
                {
                    alert(data);
                },
                error: function (data)
                {
                    alert(data.Message);
                }
            });
        });
    });
</script>
-------------------------------------------------------------------------------------------------------------------------
Save image in DB using WEBAPI
                   
Save image in DB using WEBAPI
 public IHttpActionResult Save()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (HttpContext.Current.Request.Files.Count > 0)
                    {
                        EMP emp = new EMP();
                        var file = HttpContext.Current.Request.Files["file"];
                        if (file != null)
                        {
                            file.SaveAs(HttpContext.Current.Server.MapPath("~/Image/" + Path.GetFileName(file.FileName)));
                            emp.EID = Convert.ToInt32(HttpContext.Current.Request.Form["EID"]);
                            emp.NAME = HttpContext.Current.Request.Form["NAME"];
                            int length = file.ContentLength;
                            byte[] imgbyte = new byte[length];
                            HttpPostedFile img = file;
                            img.InputStream.Read(imgbyte, 0, length);
                            emp.PHOTO = imgbyte;
                            obj.EMPs.Add(emp);
                            obj.SaveChanges();
                        }
                    }
                }
                return Ok("Data Saved.");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("EmpbyId/{EID}")]
        public HttpResponseMessage EmpbyId(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                var data = obj.EMPs.Find(EID);
                byte[] imgData = data.PHOTO;
                MemoryStream ms = new MemoryStream(imgData);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(ms);
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                return response;
            }
        }


No comments:
Post a Comment