Sunday, 31 July 2016

angular js File Upload

Controller

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Post()
        {
            var file = Request.Files[0];
            file.SaveAs(Server.MapPath("~/Image/" + Path.GetFileName(file.FileName)));
            return Json(Request.Form["EID"] + " " + Request.Form["NAME"], JsonRequestBehavior.AllowGet);
        }
    }
}
View Code


@{
    ViewBag.Title = "Index";
}

<h2>Jay Jagannath...</h2>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/angular.js"></script>
<div class="container" ng-app="app" ng-controller="ctr">
    <form class="form-horizontal" >
        <div class="form-group">
            <label class="col-lg-4 control-label">Eid</label>
            <div class="col-lg-4">
                <input type="text" class="form-control" ng-model="EID" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Name</label>
            <div class="col-lg-4">
                <input type="text" class="form-control" ng-model="NAME" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">File Upload</label>
            <div class="col-lg-4">
                <input type="file" class="form-control" id="fu"  />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label"></label>
            <div class="col-lg-4">
                <input type="button" class="btn btn-primary" value="Save" ng-click="save()" />
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    angular.module("app", []).controller("ctr", function ($scope, FileUploadService) {
        $scope.save = function () {
            var formData = new FormData();
            var file = document.getElementById("fu").files[0];
            formData.append("fu", file);
            formData.append("EID", $scope.EID);
            formData.append("NAME", $scope.NAME);
            FileUploadService.savefile(formData).then(function (d) {
                alert(d.data);
            });
        }

    }).factory("FileUploadService", function ($http) {

        var fac = {};
        fac.savefile = function (fd)
        {
            var config = {
                headers: {
                    'Content-Type': 'multipart/form-data;charset=utf-8;'
                }
            }
            return $http.post('/Home/Post', fd, config);
        }
        return fac;
    });
</script>

No comments:

Post a Comment