2

I have been struggling to upload a file using Angular JS to POST to my Java Play Framework RESTful backend as a lot of examples I have found don't apply to me.

I am confident my Angular JS code works fine but I will share it anyway:

file-upload.html

<div data-ng-controller="uploadCtrl">
    <input type="file" file-model="myFile" id="theFile" name="theFile" />
    <button data-ng-click="uploadFile()">Upload</button>
</div>

file-upload-ctrl.js

"use strict";

angular.module("pamm").controller("uploadCtrl", ["$scope", "fileUploadRepository",
    function($scope, fileUploadRepository) {

        $scope.uploadFile = function () {
            var file = $scope.myFile;
            console.dir("Ctrl: " + file);

            fileUploadRepository.uploadFile(file);
        }
    }]);

file-upload-repo.js

"use strict";

angular.module("pamm").service("fileUploadRepository", ["$q", "$log",  "$rootScope", "contextEvent", "fileUploadDao",
    function ($q, $log, $rootScope, contextEvent, fileUploadDao) {

        var fileUploadCache = [];

        (function init() {
            $rootScope.$on(contextEvent.CLEAR_CONTEXT, function clearContext() {
                fileUploadCache = [];
                $log.info("fileUploadRepository: context cleared");
            })
        })();

        this.uploadFile = function (file) {
            var waitingDialog = $$dialog.waiting("Please wait - Uploading file");

            var deferred = $q.defer();

            fileUploadDao.uploadFile(file).then(function (uploadedFile) {
                fileUploadCache.push(uploadedFile);
                $log.debug("Repo: " + uploadedFile);
                waitingDialog.close();
                deferred.resolve(uploadedFile);
            }, function (error) {
                deferred.reject(error);
                waitingDialog.close();
            });

            return deferred.promise;
        };
    }]);

The layer up from Repo

"use strict";

angular.module("pamm").service("fileUploadDal", ["$http", "$q", "$log", function ($http, $q, $log) {
    this.http = (function serviceCaller() {
        return {
            /**
             * @returns {promise}
             */
            POST: function (apiPath, fd) {
                var deferred = $q.defer();
                $http.post(apiPath, fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).then(function (results) {
                    deferred.resolve(results.data);
                }, function (e) {
                    deferred.reject(e);
                });
                return deferred.promise;
            }
        }
    })();
    $log.info("fileUploadDal:serviceCaller Instantiated");
}]);

Java

Http.MultipartFormData file = request().body().asMultipartFormData();

Where can I go next with this? Hence I can't access the name of the HTML input because of the way my Angular is written.

What can I do to file to save it the file to a directory I desire.

Thanks,

Jordan
  • 231
  • 1
  • 12
  • I think Play's documentation https://www.playframework.com/documentation/2.4.x/JavaFileUpload might be of help here. And to save a file http://stackoverflow.com/questions/8232902/java-saving-opening-file-objects. – Kris Feb 18 '16 at 12:22

2 Answers2

0

Have you tried this:

import java.io.File;

File fileFromRequest = request.body().asRaw().asFile();
fileFromRequest.renameTo(new File("path/to/dir","filename.png"));
BatteryAcid
  • 8,381
  • 5
  • 28
  • 40
0
public ServiceResult execute(final Http.MultipartFormData request)
{
    final String DIRECTORY = "C:\\SAVE_DIRECTORY\\SUB_FOLDER\\uploads";

        List<Http.MultipartFormData.FilePart> targetFiles = request.getFiles();

        for (int i = 0; i < targetFiles.size(); i++)
        {
            File file = targetFiles.get(i).getFile();

            String fileName = targetFiles.get(i).getFilename();

            file.renameTo(new File(DIRECTORY, fileName));
        }

        return new ServiceResult(Json.toJson(targetFiles));
    }
Jordan
  • 231
  • 1
  • 12