简体   繁体   English

在Angular JS中上传文件

[英]File upload in Angular JS

I am trying to do an AJAX file upload through angularjs. 我正在尝试通过angularjs上传AJAX文件。 It is telling me that my form data is improperly formatted, or something like that. 它告诉我表单数据的格式不正确或类似的格式。

This is my html: 这是我的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>

This is my directive: 这是我的指令:

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]);
                });
            });
        }
    };
}]);

This is the called uploadFile function: 这就是所谓的uploadFile函数:

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

And this is the function in my data service for uploading. 这是我的数据服务中用于上传的功能。

$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);

And finally, this is my error message: 最后,这是我的错误信息:

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.).

I also went ahead and looked at the ajax post in the console and see this: 我还继续查看控制台中的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)

This is being closed because I discovered I WAS formatting the AJAX call in the correct way. 由于我发现我以正确的方式格式化AJAX调用,因此此操作已关闭。 The problem was actually in the java that was receiving the file. 问题实际上出在接收文件的Java中。 Without making changes to the JavaScript, I managed to get a file to upload. 在不对JavaScript进行更改的情况下,我设法获得了要上传的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM