Introduction
File upload is a common feature of many applications. Sometimes we need to upload multiple files with some data.
Problem StatementI have developedan application using AngularJS and Web API 2 and I want to upload files as well as post some data. Both data and files, I want to post in a single request. How to achieve this?
SolutionThis can be done in many ways. Here I am discussing one way that I feel is the best. The following steps are required tobe performed to achieve this. In this way, I will use directive in AngularJS and Web API.
Step 1: Define AngularJS Application.
File upload is a common feature of many applications. Sometimes we need to upload multiple files with some data.
Problem StatementI have developedan application using AngularJS and Web API 2 and I want to upload files as well as post some data. Both data and files, I want to post in a single request. How to achieve this?
SolutionThis can be done in many ways. Here I am discussing one way that I feel is the best. The following steps are required tobe performed to achieve this. In this way, I will use directive in AngularJS and Web API.
Step 1: Define AngularJS Application.
- var app = angular.module("AngularApp", []);
Here, I have created a simple directive for file upload that picks up the selected files and emits "selectedFiles" event which is written in Angular controller. In this event we just add files which are selected in to the files array. Later on in this article we will look this into controller code and will discuss it.
- app.directive('uploadFiles', function () {
- return {
- scope: true, //create a new scope
- link: function (scope, el, attrs) {
- el.bind('change', function (event) {
- var files = event.target.files;
- //iterate files since 'multiple' may be specified on the element
- for (var i = 0; i < files.length; i++) {
- //emit event upward
- scope.$emit("seletedFile", { file: files[i] });
- }
- });
- }
- };
- });
- app.controller("demoController", function ($scope, $http) {
- //1. Used to list all selected files
- $scope.files = [];
- //2. a simple model that want to pass to Web API along with selected files
- $scope.jsonData = {
- name: "Jignesh Trivedi",
- comments: "Multiple upload files"
- };
- //3. listen for the file selected event which is raised from directive
- $scope.$on("seletedFile", function (event, args) {
- $scope.$apply(function () {
- //add the file object to the scope's files collection
- $scope.files.push(args.file);
- });
- });
- //4. Post data and selected files.
- $scope.save = function () {
- $http({
- method: 'POST',
- url: "http://localhost:51739/PostFileWithData",
- headers: { 'Content-Type': undefined },
- transformRequest: function (data) {
- var formData = new FormData();
- formData.append("model", angular.toJson(data.model));
- for (var i = 0; i < data.files.length; i++) {
- formData.append("file" + i, data.files[i]);
- }
- return formData;
- },
- data: { model: $scope.jsonData, files: $scope.files }
- }).
- success(function (data, status, headers, config) {
- alert("success!");
- }).
- error(function (data, status, headers, config) {
- alert("failed!");
- });
- };
- });
- <!DOCTYPE html>
- <html data-ng-app="AngularApp">
- <head>
- <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" />
- <title>AngularJS - Example</title>
- <script src="Script\angular.js"></script>
- <script src="Script\app.js"></script>
- <script src="Script\demoController.js"></script>
- <script src="Script\fileUploadDirective.js"></script>
- </head>
- <body>
- <div ng-controller="demoController">
- <b>Post JSON data and files in Same Request with AngularJS and Web API example</b>
- <br />
- <br />
- <input type="file" upload-files multiple />
- <ul>
- <li ng-repeat="file in files">{{file.name}}</li>
- </ul>
- <br />
- <br />
- <button ng-click="save()">Save</button>
- </div>
- </body>
- </html>
- public class MyDataController : ApiController
- {
- [HttpPost]
- [Route("PostFileWithData")]
- public async Task<HttpResponseMessage> Post()
- {
- if (!Request.Content.IsMimeMultipartContent())
- {
- throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
- }
- var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles");
- Directory.CreateDirectory(root);
- var provider = new MultipartFormDataStreamProvider(root);
- var result = await Request.Content.ReadAsMultipartAsync(provider);
- var model = result.FormData["jsonData"];
- if (model == null)
- {
- throw new HttpResponseException(HttpStatusCode.BadRequest);
- }
- //TODO: Do something with the JSON data.
- //get the posted files
- foreach (var file in result.FileData)
- {
- //TODO: Do something with uploaded file.
- }
- return Request.CreateResponse(HttpStatusCode.OK, "success!");
- }
- }
var file = Request.Files[0];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/File/"), fileName);
file.SaveAs(path);
Application oExcel = new Application();
string filepath = path;
Workbook WB = oExcel.Workbooks.Open(filepath);
string ExcelWorkbookname = WB.Name;
List<string> listMT = new List<string>();
foreach (Worksheet obj in WB.Worksheets)
if(obj.Name.Substring(0,2)=="MT")
listMT.Add(obj.Name.Substring(3));
Worksheet wks = (Worksheet)WB.Worksheets[1];
int rows= wks.Rows.Count;
int cols= wks.Columns.Count;
string firstworksheetname = wks.Name;
var firstcellvalue = ((Range)wks.Cells[1, 1]).Value;
return Json(listMT, JsonRequestBehavior.AllowGet);
----------------------------------------------------------------------------------------------
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>From</legend>
<div class="form-group">
<label class="control-label col-lg-4">RCN/ACN Excel File Upload</label>
<div class="col-lg-4">
<input type="file" id="Upload" value="Upload" class="form-control" />
<span id="errorMessage" style="color:red"></span>
</div>
<div class="col-lg-4">
<input type="button" id="btnUpload" value="Upload" class="btn btn-primary" style="width:80px" />
</div>
</div>
</fieldset>
<fieldset class="fields">
<legend>For</legend>
<div class="form-group">
<label class="control-label col-lg-4">Product</label>
<div class="col-lg-4">
<span class="cbGroup"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" class="btn bg-primary" value="Convert Into XML" />
</div>
</div>
</fieldset>
</form>
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#Upload').change(function () {
if ($('#Upload').val() == "") {
$('#errorMessage').text('Please select a file');
return false;
}
else {
$('#errorMessage').text('');
}
}); $('.fields').hide();
$('#btnUpload').click(function () {
if ($('#Upload').val() == "") {
$('#errorMessage').text('Please select a file');
return false;
}
else {
$('#errorMessage').text('');
}
var formData = new FormData();
var file = document.getElementById("Upload").files[0];
formData.append("rcexcel", file);
$.ajax({
type: "POST",
url: '/RCTOXML/Fetchexcelfile',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
$('.fields').show();
$.each(data, function (i, j) {
$('.cbGroup').append("<input type='checkbox' class='cb' /> " + j + "<br>");
});
},
error: function (error) {
alert("errror");
}
});
});
});
</script>
-----------------------------------------------------------------------------------------------
controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WDOne.Models;
using Microsoft.Office.Interop.Excel;
namespace WDOne.Controllers
{
public class RCTOXMLController : Controller
{
// GET: RCTOXML
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Fetchexcelfile()
{
try
{
var file = Request.Files[0];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/RCExcelFile/"), fileName);
if (!System.IO.File.Exists(path))
{
file.SaveAs(path);
}
int index = 0, Tr = 0, Pv = 0, Fopv = 0;
string cvalue = string.Empty;
Range objRange = null;
Application app = new Application();
Workbook WB = app.Workbooks.Open(path);
List<string> listMT = new List<string>();
foreach (Worksheet obj in WB.Worksheets)
{
if (obj.Name.Substring(0, 2) == "MT")
{
for (index = 1; index < obj.Columns.Count; index++)
{
objRange = obj.Cells[1, index];
cvalue = objRange.Text;
string[] tvalue = cvalue.Split('\n');
cvalue = tvalue[0].Trim() + " " + tvalue[1].Trim();
if (cvalue.Trim() == "Table Revison".Trim())
Tr = index;
if (cvalue.Trim() == "Parameter Version".Trim())
Pv = index;
if (cvalue.Trim() == "Final Outgoing Parameter Version".Trim())
{
Fopv = index;
break;
}
}
listMT.Add("Table revision : " + ((Range)obj.Cells[3, Tr]).Text + " Incoming version : " + ((Range)obj.Cells[3, Pv]).Text + " Outgoing version : " + ((Range)obj.Cells[3, Fopv]).Text);
}
}
return Json(listMT, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
}
}
----------------------------------------------------------------------------------------------
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>From</legend>
<div class="form-group">
<label class="control-label col-lg-4">RCN/ACN Excel File Upload</label>
<div class="col-lg-4">
<input type="file" id="Upload" value="Upload" class="form-control" />
<span id="errorMessage" style="color:red"></span>
</div>
<div class="col-lg-4">
<input type="button" id="btnUpload" value="Upload" class="btn btn-primary" style="width:80px" />
</div>
</div>
</fieldset>
<fieldset class="fields">
<legend>For</legend>
<div class="form-group">
<label class="control-label col-lg-4">Product</label>
<div class="col-lg-4">
<span class="cbGroup"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" class="btn bg-primary" value="Convert Into XML" />
</div>
</div>
</fieldset>
</form>
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#Upload').change(function () {
if ($('#Upload').val() == "") {
$('#errorMessage').text('Please select a file');
return false;
}
else {
$('#errorMessage').text('');
}
}); $('.fields').hide();
$('#btnUpload').click(function () {
if ($('#Upload').val() == "") {
$('#errorMessage').text('Please select a file');
return false;
}
else {
$('#errorMessage').text('');
}
var formData = new FormData();
var file = document.getElementById("Upload").files[0];
formData.append("rcexcel", file);
$.ajax({
type: "POST",
url: '/RCTOXML/Fetchexcelfile',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
$('.fields').show();
$.each(data, function (i, j) {
$('.cbGroup').append("<input type='checkbox' class='cb' /> " + j + "<br>");
});
},
error: function (error) {
alert("errror");
}
});
});
});
</script>
-----------------------------------------------------------------------------------------------
controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WDOne.Models;
using Microsoft.Office.Interop.Excel;
namespace WDOne.Controllers
{
public class RCTOXMLController : Controller
{
// GET: RCTOXML
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Fetchexcelfile()
{
try
{
var file = Request.Files[0];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/RCExcelFile/"), fileName);
if (!System.IO.File.Exists(path))
{
file.SaveAs(path);
}
int index = 0, Tr = 0, Pv = 0, Fopv = 0;
string cvalue = string.Empty;
Range objRange = null;
Application app = new Application();
Workbook WB = app.Workbooks.Open(path);
List<string> listMT = new List<string>();
foreach (Worksheet obj in WB.Worksheets)
{
if (obj.Name.Substring(0, 2) == "MT")
{
for (index = 1; index < obj.Columns.Count; index++)
{
objRange = obj.Cells[1, index];
cvalue = objRange.Text;
string[] tvalue = cvalue.Split('\n');
cvalue = tvalue[0].Trim() + " " + tvalue[1].Trim();
if (cvalue.Trim() == "Table Revison".Trim())
Tr = index;
if (cvalue.Trim() == "Parameter Version".Trim())
Pv = index;
if (cvalue.Trim() == "Final Outgoing Parameter Version".Trim())
{
Fopv = index;
break;
}
}
listMT.Add("Table revision : " + ((Range)obj.Cells[3, Tr]).Text + " Incoming version : " + ((Range)obj.Cells[3, Pv]).Text + " Outgoing version : " + ((Range)obj.Cells[3, Fopv]).Text);
}
}
return Json(listMT, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
}
}
No comments:
Post a Comment