Fetching image files from Angular JS in a servlet

On my website, users have the ability to upload images. I am using AngularJS to post the data to a specific URL via a POST request. My question is, how can I retrieve this data in a Java servlet? My goal is to save the uploaded image in a database. Is this the correct way to go about completing this task?

//Controller
app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log('file is ' + (file));
    var uploadUrl = "/Angular/login";
    fileUpload.uploadFileToUrl(file, uploadUrl);
};

}]);
//Service
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}
}]);

//directive
app.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]);
            });
        });
    }
};
}]);

How do I fetch the above posted data within a Java servlet?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


}

Answer №1

If you're looking for a reliable solution that is compatible with older servlet versions, Apache Commons FileUpload is a great option.

For more information, visit

AngularJS Client Implementation

<!DOCTYPE html>
<html ng-app="FileuploadApp">
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
angular
    .module("FileuploadApp", [])
    .controller("FileCtrl", function($scope, $http) {
        $scope.upload = function() {
            var fd = new FormData();
            fd.append("file", $scope.file);
            $http({
                withCredentials: true,
                method: 'POST',
                url: './fileupload',
                data: fd,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            });
        }
    })
    .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]);
                });
            });
        }
    };
}]);
</script>
</head>
<body ng-controller="FileCtrl">
    <input type="file" file-model="file"/>
    <input type="button" value="Upload!" ng-click="upload();">
</body>
</html>

Java Servlet Code Sample

@WebServlet(urlPatterns="/fileupload")
public class FileuploadTestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletContext servletContext = this.getServletConfig().getServletContext();
                File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
                factory.setRepository(repository);
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                List<FileItem> files = fileUpload.parseRequest(req);

                if (files != null && !files.isEmpty()) {
                    for (FileItem item : files) {
                        System.out.println("* " + item.getName() + " " + item.getSize() + " bytes.");
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

        }

    }
}

Console Output:

* cthulhu.bin 42 bytes.

Answer №2

To extract the raw data from a servlet request, simply utilize the following code:

InputStream stream = request.getInputStream();

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

execute regular javascript with angualrjs

Seeking to integrate legacy javascript code for affiliate tracking into an angularjs app <script type="text/javascript"> //<![CDATA[ /*** Do not change ***/ var AWIN = {}; AWIN.Tracking = {}; AWIN.Trackin ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

Issue encountered while utilizing WebDriverWait with the ExpectedCondition function presenceOfElementLocated()

I encountered an error while compiling: public static WebDriverWait wait = null; wait = new WebDriverWait(driver, 120); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(HomeScreen.tabHome_ID))); I am currently working with IntelliJ IDE. Err ...

Access your Angular 5 application as a static webpage directly in your browser, no server required!

I need to run an Angular 5 application in a browser by manually opening the index.html file without the use of a server. My client does not have access to any servers and simply wants me to provide a package (dist folder) for them to double-click on the in ...

What are the steps for sharing a json file?

{ "entry": { "city_id": "1234", "city_name": "California" } } Here is the JSON data that needs to be submitted from an HTML form to a content management system API. The form contains two text boxes for capturing city_id and city_name en ...

I keep seeing this strange [object HTMLSpanElement] appearing on my HTML page

Thanks for the help, the issue has been resolved and I appreciate your valuable time! ...

"Enhance your website with the dynamic duo of Dropzone

Currently, I am utilizing dropzone.js and loading it through ajax. I have assigned my menu ID as "#menu". The uploaded file should display in "#div1". Unfortunately, the callback function is not functioning properly. In an attempt to troubleshoot, I repl ...

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

What is the best JavaScript framework for implementing client-side hyphenation?

Looking to improve my website's readability, I want to implement client-side hyphenation using JavaScript for longer texts. Although CSS3 hyphenation is preferred, it's not always available. So far, I've been using Hyphenator.js, which, whi ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Conflicting issues with jQuery's load() method

I am facing an issue with loading two HTML pages into a single div. I have index.html and try.html in the root folder, where try.html is loaded into index.html's div (#content) when Button 01 is clicked on index.html. The problem arises when I further ...

Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview Here is the code snippet: Controller: app.controller('MainCtrl', function($scope) { ...

What could be the reason that a basic click function fails to locate the selector?

I have created a quick JavaScript module that opens an image and fades out a container to reveal the image. The HTML markup for the image looks like this: <div style="margin-bottom:1px;" class="rsNavItem rsThumb front"> <di ...

The architecture of Laravel and AngularJS views

Recently, I've delved into the world of angularjs in hopes of using it for my new project. However, I'm facing a roadblock when it comes to structuring the view. I'm unsure about how to go about building it. Would it be acceptable to create ...

Adjusting Renderer Size in ThreeJS for Fullscreen Display

After creating a ThreeJS application designed for a 4:3 layout with multiple buttons and features, I decided to enable Fullscreen mode using THREEx.Fullscreen.js. Although the Fullscreen mode is functioning properly, a new issue arose - the renderer size(x ...

Learn how to incorporate a HTML page into a DIV by selecting an Li element within a menu using the command 'include('menu.html')'

I have a website with both 'guest' and 'user' content. To handle the different menus for logged-in and logged-out users, I created menuIn.html and menuOut.html files. These menus are included in my MainPage.php using PHP logic as sugges ...

Utilize the composite primary key of an Entity within Typeorm for efficient data retrieval

I am working with the following database entities: @Entity() class Team { @PrimaryGeneratedColumn() id: string @PrimaryColumn() teamName: string @OneToMany(() => Player, player => player.team) players: Player[] } @Entity() class Player ...

Decoding multiple data with jQuery on the server-side

Scenario: A situation arises where I am utilizing a jQuery.ajax call to send three arrays to the server for database storage. The challenge lies in decoding the combined data object on the server side and breaking it back into the original three arrays. ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...