Introduction
File upload is a common feature of many applications. Sometimes we need to upload multiple files with some data.
Problem Statement
I 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?
Solution
This 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] });
- }
- });
- }
- };
- });
Next step is to define the angular controller. In the controller, I have defined “selectedFile” event which is emitted from the directive. In this event we just push the selected files in to array. Later on this will used to post the files. I have also defined dummy JSON data which I want to post to Web API with selected files. Save method of the controller is use angular http service to post data and files. The transformRequest is http service property and it can be a single function that returns the transformed value. Here we just are overriding the default Transformations. This will allow us to change way of data send up to the server.
- 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!");
- });
- };
- });
Next step is to define the markup.
- <!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>
In this step, I have created Web API controller with standard way. In following highlight code, we get the our posted JSON data as well as posted iles.
- 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!");
- }
- }

Summary
The way defined in this article is useful in upload the file along with the data. Hope this will help you.


Imad SiddiquiPosted May 14, 2020, 2:05 AM EDT
Can we try the same C# code without a path to upload the file? I don't want to upload the path, I only want to read the file and JSON data and push it into the DB.
Anubhav MishraPosted Mar 3, 2020, 7:24 PM EST
I followed the above steps apart from the WEB API part. The problem is scope.$emit is emitting the number of event(selectedFile) correctly as per the length of files however, $scope.$on is catching this event 3 times for each file. I am unable to understand why. Can you help me with it?
Abhishek GuptaPosted Aug 14, 2019, 10:39 PM EDT
Nice article. for Angular JS 1.6.4 compatible code: $scope.submiCustomerDetails = function () { var jsonData = { firstName: $scope.firstName, middleName : $scope.middleName, lastName : $scope.lastName, email : $scope.email, comments : $scope.comments, files : $scope.files }; var url = "<your service url>>"; var config = { 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 } }; $http.post(url,jsonData,config) .then( function(response) { $log.log('success'); }, function error(response) { $log.log('error'); }); };
Punit SinghiPosted Jul 26, 2019, 8:51 AM EDT
Nice article, but you are using server.mappath, what happens if server are located different location so physical location won't match... wouldn't it created issue?
biswaranjan dasPosted Mar 13, 2019, 11:50 AM EDT
Files are created with encrypted name without extension in the concern folder like BodyPart_65f65fde-bf77-4064-a3d3-d42a2cfabf40 , BodyPart_c28661a8-250f-4301-b07b-3027163dc3f9
muqofa ridaPosted Feb 18, 2019, 4:49 PM EST
Thank you it`s help me
anoop guptaPosted Sep 2, 2018, 1:52 AM EDT
File Not get when Is ajax hit to API. Can you please give me your contact number
anoop guptaPosted Sep 1, 2018, 12:08 AM EDT
Why content type undefined
anoop guptaPosted Aug 31, 2018, 11:30 PM EDT
BAKWAS Article always go to error
anoop guptaPosted Aug 31, 2018, 11:20 PM EDT
File not get in API
Viknaraj ManogararajahTOP 100Posted Aug 7, 2018, 7:15 AM EDT
nice article thank you for sharing....
revathi sharmiPosted Aug 6, 2018, 9:30 PM EDT
Need to return some data with success on this. how i can do that?
revathi sharmiPosted Aug 6, 2018, 9:29 PM EDT
Always its going to error section.
MD IslamPosted May 5, 2018, 1:23 AM EDT
Hi Jignesh Trivedi I am getting 404 error saying like POST http://localhost:52224/PostFileWithData 404 (Not Found) at console
Sabab ZulfikerPosted Apr 13, 2018, 2:41 AM EDT
How can I extract the attributes like name, comments from result.FormData["jsonData"] , so that I can store them into database. And what is the required operation for uploading the files into database??
anubha agrawalPosted May 2, 2017, 1:37 AM EDT
Hi Jignesh, is it possible to post json values to web services not web api controller?
Manveer SinghPosted Sep 27, 2016, 10:54 PM EDT
Hi Jignesh,can you please share the code for as in case of different files with data as Fields, 1: Employee Name, 2. Photo(Image), 3. Signature(Image).
Pradeep SahooPosted May 9, 2016, 6:22 PM EDT
Nice . Thanks for sharing
Vivek KumarPosted Apr 28, 2016, 10:53 AM EDT
Good one
Kuppurasu NagarajTOP 100Posted Apr 22, 2016, 8:10 AM EDT
Nice Sharing..
Debasis SahaTOP 100Posted Apr 21, 2016, 9:29 AM EDT
Nice One..
Gowtham KTOP 100Posted Apr 21, 2016, 9:22 AM EDT
Good One, Thanks for sharing
Rahul Kumar SaxenaTOP 100Posted Apr 21, 2016, 5:04 AM EDT
Good one
Vignesh ManiTOP 100Posted Apr 21, 2016, 4:23 AM EDT
Nice one
Shakti Singh DulawatPosted Apr 21, 2016, 3:53 AM EDT
Thanks for this article, just want to know when you pass two request from single event does it slow down performance of application ?