在Angular JS中上传文件

时间:2014-07-02 19:05:56

标签: javascript jquery ajax angularjs

我正在尝试通过angularjs上传AJAX文件。它告诉我,我的表单数据格式不正确,或类似的东西。

这是我的HTML:

<TR>
    <TD class="labelWide" nowrap="nowrap">Upload PDF</TD>
    <TD class="required">&nbsp;</TD>
    <TD class="data">
        <input type="file" npr-uploader="temporary_upload">
        <button ng-click="uploadFile('pdf')">Load File</button><BR>
        <span ng-repeat="fileItem in data.pdfFiles">{{fileItem.filename}}<BR></span>
    </TD>
</TR>

这是我的指示:

nprDirectives.directive('nprUploader', ['$parse', function($parse){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.nprUploader);
            var modelSetter = model.assign;
            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

这是被称为uploadFile的函数:

$scope.uploadFile = function(arg_type){
    $scope.data.uploadFile($scope.temporary_upload, arg_type);
};

这是我的数据服务中的上传功能。

$scope.uploadFile = function(arg_file,arg_type,arg_key){
    var fd = new FormData();
    fd.append("attachment", arg_file);

    var urlType = "other";
    if(arg_type == "pdf"){
        urlType = "pdf";
    }

    $http.post( contextPath+'/uploadFile/ajax/upload/'+urlType, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
.success(stuff happens)
.error(stuff happens);

最后,这是我的错误消息:

HTTP Status 400 - Please check your Data
type:  Status Report
message:  Please check your Data
description:  The request sent by the client was syntactically incorrect (Please check your Data.).

我也继续看着控制台中的ajax帖子,看看:

-----------------------------168221372516176 
Content-Disposition: form-data; name="attachment"; filename="busicard.pdf" 
Content-Type: application/pdf

%PDF-1.4 
(etc lots of gobblygook because PDF with image)

1 个答案:

答案 0 :(得分:0)

这是关闭的,因为我发现我以正确的方式格式化AJAX调用。问题实际上是在接收文件的java中。在不对JavaScript进行更改的情况下,我设法获取了要上传的文件。