Transferring data to server using AngularJS and Java Servlet Technology

I am currently facing a challenge in developing a webpage that enables file uploads from a local machine to a server using AngularJS and Java Servlet. My approach involves sending data to the server using $http.post and attempting to read the file data using apache commons-fileupload. However, I have encountered an issue where the file data is not sent in the expected multipart/form-data format, preventing commons-fileupload from properly detecting the file data on the server side. Manually setting {headers:{'Content-Type':'multipart/form-data'}} in the post request results in an exception being thrown.

Below is the HTML page and JS file I am utilizing:

HTML Page:

<!DOCTYPE html>
<html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="js/upload.js"></script>
    <head>
        <title>Admin</title>
    </head>
    <body ng-app="uploadApp" ng-controller="UploadCtrl">
        <form name="upload" class="form" data-ng-submit="addFile()">
            <p>Please specify a file, or a set of files:<br>
            <input type="file" name="file" onchange="angular.element(this).scope().attachedFile(this)" /></p>
            <button type="submit">Upload</button>

        </form>
    </body>
</html>

JS file:

var app=angular.module('uploadApp',[]);

app.controller('UploadCtrl', ['$scope','$http',function($scope,$http) {
    $scope.attachedFile = function(element) {
        $scope.$apply(function($scope) {
            $scope.file = element.files[0];   
        });     
        console.log('file attached');
    };

    $scope.addFile = function() {
        var url = '/upload';
        var fd = new FormData();        
        fd.append("file",$scope.file);          
        $http.post(url, fd)
        .success(function(data, status, headers, config) {
            console.log('success');
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        })
    };
}]) 

In examining the issue, I observed the data received on the server side in the following format:

------WebKitFormBoundaryXXXXXXXXXXXXX
Content-Disposition: form-data; name="file"; filename="XXX.txt"
Content-Type: text/plain

filedata
------WebKitFormBoundaryXXXXXXXXXXXXX--

The problem lies in the generated FormData not specifying Content-Type: multipart/form-data, defaulting instead based on the file extension, thus causing issues with commons-fileupload on the server side.

I am seeking advice on a possible solution to this issue. Is there a way to manually set the content type to multipart/form-data in the FormData/request created, or is there an alternative method/library to parse the received data on the server side?

Answer №1

After making some adjustments to the post request, I was finally able to get it working as intended.

$http.post(url, fd,{headers: {'Content-Type': undefined}})

With this modification, I am now able to successfully retrieve and save files on the server side using file upload. However, I am interested in including additional key/value pairs in the request, as shown below.

var fd = new FormData();        
fd.append("file",$scope.file);     
fd.append("ID","abcxxx");
$http.post(url, fd,{headers: {'Content-Type': undefined}})

I am curious to learn how I can access these key/value pairs that are being sent along with the file data when using commons-fileupload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

What is the reason behind the success of this location?

Curious about the functionality of this particular JavaScript code with its corresponding HTML structure: function getCityChoice() { const location = document.querySelector("form").location.value; console.log(location) } <form name="reserve" a ...

Maya model being loaded using Three.js

I've been following a tutorial on how to load Maya models using Three.js, which you can find here. Everything is going smoothly, but the tutorial only covers loading models with a single texture. Below is the source code snippet from the tutorial: ...

Having difficulty implementing DragControls

My experience with three.js is at a beginner level, and I recently attempted to incorporate a feature allowing the dragging of a 3D model. During this process, I encountered DragControl but faced difficulty implementing it in my code. Upon using new DragCo ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

I am facing an issue where the URL generated in the Controller in Laravel is not functioning properly when

After escaping the single quote, I included a URL link inside the Controller and passed it through json_encode. However, when I clicked on the URL link, it did not work and showed this: https://i.sstatic.net/3GIq1.png The URL appeared like this: http: ...

Can Syncano handle importing .xls files?

We are interested in utilizing Syncano to develop a serverless application. We are in need of importing a .xls file from the user and extracting parameters such as number, name, price, etc. Is this feasible with Syncano? ...

How can you conceal an object based on specific conditions in JavaScript?

In my JavaScript code, I am working with an object that stores multiple values. However, I want to be able to hide a specific object under certain conditions. Here is the data structure: $scope.sort={ National : { prop: "Country", classes: { md: ...

Does Peerjs exclusively cater to one-on-one webrtc communication?

Can PeerJS be used to implement one-to-many audio communication with WebRTC? I'm currently using Socket.io with Node.js. Is this sufficient for WebRTC integration? As a beginner in WebRTC, could you recommend some options for implementin ...

Tips on how to modify a select option in vue based on the value selected in another select

My Web Api has methods that load the first select and then dynamically load the options for the second select, with a parameter passed from the first selection. The URL structure for the second select is as follows: http://localhost:58209/api/Tecnico/Tanq ...

How to toggle the display of a div by its id using index in Javascript

Currently, I am encountering a problem with toggling the div containers. When I click on the video button, I want the other divs to close if they are already open. However, due to the toggling mechanism, if a div is closed and I click on the corresponding ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

Inconsistencies in spacing between shapes bordering an SVG Circle using D3.js are not consistent across platforms

After creating a SVG circle and surrounding it with rectangles, I am now attempting to draw a group of 2 rectangles. The alignment of the rectangle combo can either be center-facing or outside-facing, depending on the height of the rectangle. However, I am ...

The panel's fullscreen feature crashes when exiting after triggering the 'resize' function

I'm facing an issue with a popup window that automatically goes into fullscreen mode. There are two buttons - one to exit fullscreen and another to simply close the window. When the window is in fullscreen, the exit button works perfectly. However, i ...

Limitations of GitHub's rate limiting are causing a delay in retrieving user commit history

I have developed a code snippet to retrieve the user's GitHub "streak" data, indicating how many consecutive days they have made commits. However, the current implementation uses recursion to send multiple requests to the GitHub API, causing rate-limi ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

What could be the reason for the malfunction of the "includes" function in my JavaScript snake game

As a beginner in JavaScript, I've been learning CSS and HTML as well. I decided to practice my skills by creating a snake game without following any tutorials. I know my code might not be the best and lacks good practices, but I'm just doing this ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Is there a way to search through a list and apply filters based on parameters found within a nested object?

I have a list that needs to be filtered based on parameters from advancedSearchFilters, which contains nested objects. The goal is to return a list that matches all or any of the specified parameters. const list = [ { additionalPrices: 0, clien ...