简体   繁体   中英

File upload in Angular JS

I am trying to do an AJAX file upload through angularjs. It is telling me that my form data is improperly formatted, or something like that.

This is my 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:

$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:

-----------------------------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. The problem was actually in the java that was receiving the file. Without making changes to the JavaScript, I managed to get a file to upload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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