0

I have a page where user can upload image. I am posting the data to the url using the post request of angular js. My doubt is how do i retrieve this data in servlet. I want save the image in the database. Please let me know if this is the correct approach to perform this activity

//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 should i retrieve the above posted data in java servlet..?

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


}
axn7975
  • 107
  • 1
  • 3
  • 16
  • 1
    Servlet's code for parsing multipart/form-data requests is not different from when using a normal HTML form. – BalusC Jul 02 '15 at 20:02

2 Answers2

0

You can safely use Apache Commons FileUpload for this, which will work with older servlet versions as well.

Check http://commons.apache.org/proper/commons-fileupload/using.html

AngularJS Client Code

<!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

@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.
neuro_sys
  • 805
  • 7
  • 13
-1

You can use InputStream stream = request.getInputStream(); to read the raw data from servlet request

Naresh Vavilala
  • 598
  • 4
  • 14