DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Upload and Retrieve Files/Images Using Spring Boot, Angular, and MySQL
  • Leveraging Salesforce Using a Client Written In Angular
  • Deep Links With Angular Routing and i18n in Prod Mode
  • Spring Boot File Upload Example With MultipartFile [Video]

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Designing a Java Connector for Software Integrations
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • How Trustworthy Is Big Data?
  1. DZone
  2. Coding
  3. Frameworks
  4. File Upload Using AngularJS and Spring

File Upload Using AngularJS and Spring

In this article, we discuss how to use these two popular frameworks to pull in data from an external source and use it to populate the backend of our web app.

By 
Vishal Srinivasan user avatar
Vishal Srinivasan
·
Sep. 19, 17 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
32.0K Views

Join the DZone community and get the full member experience.

Join For Free

Hi, everyone!

Over the past few days, several people have asked me how to create a SPRING-MVC file upload using AngularJS. So I thought I'd write a post about it where I create working code that fetches a multipart file from the front-end and process this data in the backend.

To begin, you need to know the basics of AngularJS and RESTful Web Services.

The project is going to be created using the Maven Build Tool. So you may need to know the basics of MAVEN too. If not, then you don't need to worry. Install the jar externally and run it with the build tool you like (ANT, etc).

Let's Begin:

Here are the dependencies in POM.XML that are needed for our code. If you're not using Maven, then download the “Apache common” JARs externally. Here is an easy way to do it. Go to this URL and download the commons-io dependency jar. Inside that, you can search the artifactId mentioned in the POM.XML and can fetch the required JAR from that site.

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>

Now, we will create a bean to add the maximum file upload limit. Here is the code for that. Place this in Spring configuration XML. This file is more commonly called SPRING-SERVLET.XML

Now, let's create a controller for fetching the file from the frontend and to process that file and store it in a specified path. Here is a code for that:

@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@Produces(MediaType.APPLICATION_JSON) 
public Data continueFileUpload(HttpServletRequest request, HttpServletResponse response){
        MultipartHttpServletRequest mRequest;
String filename = "upload.xlsx";
try {
   mRequest = (MultipartHttpServletRequest) request;
   mRequest.getParameterMap();

   Iterator itr = mRequest.getFileNames();
   while (itr.hasNext()) {
        MultipartFile mFile = mRequest.getFile(itr.next());
        String fileName = mFile.getOriginalFilename();
        System.out.println(fileName);

        java.nio.file.Path path = Paths.get("C:/Data/DemoUpload/" + filename);
        Files.deleteIfExists(path);
        InputStream in = mFile.getInputStream();
        Files.copy(in, path);
 }
   } catch (Exception e) {
        e.printStackTrace();
   }
return null;
}

Here I am storing that EXCEL FILE in “C:/Data/DemoUpload/” with a modified filename (upload.xlsx). This uses two items: one is fetching the file as a map using MultipartHttpServletRequest, and one is saving that file using the Input stream buffer. This will copy the file that was created and put it into the place that we specify.

Now let's create a front-end for clients. Here is a simple script for it:

<div>
 <div class="jumbotron"><input type="file" /> <button>upload me</button></div>
 &nbsp;
 <div class="alert alert-danger fade in"><a class="close" href="#" data-dismiss="alert">×</a> <strong>Errors!</strong> {{errors.value}}</div>
 </div>
 <script>
 var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['$parse', function ($parse) {
 return {
 restrict: 'A',
 link: function(scope, element, attrs) {
 var model = $parse(attrs.fileModel);
 var modelSetter = model.assign;

element.bind('change', function(){
 scope.$apply(function(){
 modelSetter(scope, element[0].files[0]);
 });
 });
 }
 };
 }]);

myApp.service('fileUpload', ['$q','$http', function ($q,$http) {
 var deffered = $q.defer();
 var responseData;
 this.uploadFileToUrl = function(file, uploadUrl){
 var fd = new FormData();
 fd.append('file', file);
 return $http.post(uploadUrl, fd, {
 transformRequest: angular.identity,
 headers: { 'Content-Type' : undefined}
 })
 .success(function(response){

/* $scope.errors = response.data.value; */
   console.log(response);
   responseData = response;
   deffered.resolve(response);
   return deffered.promise;
   })
   .error(function(error){
   deffered.reject(error);
   return deffered.promise;
   });

}

this.getResponse = function() {
 return responseData;
 }

}]);

myApp.controller('myCtrl', ['$scope', '$q', 'fileUpload', function($scope, $q, fileUpload){
 $scope.dataUpload = true;
 $scope.errVisibility = false;
 $scope.uploadFile = function(){
     var file = $scope.myFile;
     console.log('file is ' );
     console.dir(file);

      var uploadUrl = "<give-your-url>/continueFileUpload";
       fileUpload.uploadFileToUrl(file, uploadUrl).then(function(result){
       $scope.errors = fileUpload.getResponse();
       console.log($scope.errors);
       $scope.errVisibility = true;
       }, function(error) {
       alert('error');
       })

};
 }]);
 </script>

Here we created a directive and a service for fetching the data and putting it in the backend. We used $q for asynchronous calls. This is called a PROMISE in AngularJS. In our next course, I will surely describe how to create promises and what asynchronous calls are. Change the “ ” place with your server URL and run the code to upload an Excel sheet to your backend.

Upload AngularJS Spring Framework

Published at DZone with permission of Vishal Srinivasan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upload and Retrieve Files/Images Using Spring Boot, Angular, and MySQL
  • Leveraging Salesforce Using a Client Written In Angular
  • Deep Links With Angular Routing and i18n in Prod Mode
  • Spring Boot File Upload Example With MultipartFile [Video]

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!