使用angularjs

时间:2015-09-01 13:06:32

标签: javascript angularjs

我是角色的新手,我尝试上传文件,但我得到了错误的请求错误 我尝试所有在线示例,但我只得到错误的请求错误。 我在下面显示我的代码

这是我的客户端部分

<div ng-controller = "myCtrl">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
</div>



myApp.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(){
        });
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' + JSON.stringify(file));
        var uploadUrl = "/customers/17/artifacts";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };

}]);

这是我的服务器端部分

控制器部分

@RequestMapping(value = "/customers/{accountNumber}/artifacts", method = RequestMethod.POST)
    void uploadCustomerArtifact(@PathVariable Long accountNumber, @RequestParam("artifact") MultipartFile uploadfile, HttpServletRequest request, HttpServletResponse response) {
        log.info("RestController UploadFile Called");

        artifactService.uploadArtifacts(accountNumber, uploadfile, request, response);
    }

服务部分

@Transactional
    void uploadArtifacts(Long accountNumber, MultipartFile uploadfile, HttpServletRequest request, HttpServletResponse response)
    {
        BufferedOutputStream stream
        try {

            Validate.assertNotNull(accountNumber,"field.required","Customer account number is mandatory");

            Customer existingCustomer = customerRepository.findByAccountNumber(accountNumber);
            Validate.assertNotNull(existingCustomer, "not.exist", "Customer account number doesn't exist");

            Artifact myArtiFact = new Artifact();
            myArtiFact.name = uploadfile.getOriginalFilename();
            myArtiFact.type = uploadfile.getContentType();
            myArtiFact.content = uploadfile.bytes

            String contentType = request.getServletContext().getMimeType(FilenameUtils.getName(uploadfile.getOriginalFilename()));

            println "contentType : "+contentType

            existingCustomer.addArtifact(myArtiFact);

            customerRepository.save(existingCustomer);
            log.info("UploadArtifacts Success");

        }
        catch (Exception e) {
            throw e;
        }
        finally
        {
            if(stream != null)
            {
                stream.close();
            }
        }       
    }

0 个答案:

没有答案