使用angularjs和servlet

时间:2016-10-05 11:14:12

标签: java angularjs servlets

我正在尝试从html上传图片 - > angularjs - > servlet - >数据库(这里使用post方法)。

我的HTML是

<form class="formCls" ng-submit="addTravel()">
                    <input type="text" placeholder="Title" ng-model="travel.title"><br>
                    <input type="text" placeholder="Place from" ng-model="travel.from"><br>
                    <input type="text" placeholder="Place To" ng-model="travel.to"><br>
                    <input type="text" placeholder="With" ng-model="travel.withFrnd"><br>
                    <input type="file" ng-model-instant onchange="angular.element(this).scope().imageUpload(this)"><br>
                    <input type="submit" id="formSubmit" value="Submit">&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="reset" value="Reset"><br><br>
                </form>

我的app.js是

$scope.imageUpload = function(element) {
    var reader = new FileReader();
    reader.onload = $scope.imageIsLoaded;
    reader.readAsDataURL(element.files[0]);
}

$scope.imageIsLoaded = function(e) {
    $scope.$apply(function() {
        $scope.stepsModel.push(e.target.result);
    });
}
$scope.addTravel = function() {
    alert($scope.travel);
    console.log($scope.stepsModel);

    $http({
        method : 'POST',
        url : 'NewTravel',
        headers : {
            'Content-Type' : undefined
        },
        params : {
            title : $scope.travel.title,
            from : $scope.travel.from,
            to : $scope.travel.to,
            withFriend : $scope.travel.withFrnd,
            imageArray : $scope.stepsModel
        }
    }).success(function(data, status, headers, config) {
        console.log("I am done");
        console.log("data " + data);
        console.log(status);
        console.log(headers);
        console.log(config);
        $scope.uploaded = 'uploaded Successfully';
        $scope.travel = {};
        somethingChanged = false;
    }).error(function(data, status, headers, config) {
        console.log("You need to nail me");
        $scope.uploaded = 'Sorry';
    });
}

并在servlet中将其作为

@Override
protected void service(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    System.out.println("I came to servlet");
     System.out.println("Image Array"+request.getParameterValues("imageArray"));
    String tvTitle = request.getParameter("title");
    String tvFrom = request.getParameter("from");
    String tvTo = request.getParameter("to");
    String tvWith = request.getParameter("withFriend"); 
    String tvImage = request.getParameterValues("imageArray");


    System.out.println(tvTitle+"\n"+tvFrom+"\n"+tvTo+"\n"+tvWith+"\n"+tvImage);
}

}

如果我这样做,我无法在服务器端获取数据,我得到错误为con_Aborted或400错误请求。

如何上传图像以及如何在servlet中获取该图像。是在servlet中获取图像的正确方法

0 个答案:

没有答案