Umar Abbas
Umar Abbas

Reputation: 4161

File upload error code 1 in ng-cordova filetransfer plugin

I am working on a cross platform mobile App using visual studio 2015 rc's Apache cordova template and ionic framework.App's main functionality is to upload images from camera to a remote hosting. for that purpose i am using File-transfer plugin in angular controller and RestApi (ASP.net webapi) at server side.

but while testing it continuously giving me this error.

Exception:

ERROR: { "code":1,"source":"api/fileupload/uploadfile","target":"api/fileupload/uploadfile","http_status":null,"body":null,"exception":{"description":Access is denied"...}

here is my controller code

.controller("ImageUploadCtrl", function($scope, $cordovaFileTransfer) {

    $scope.upload = function() {
        var options = {
            fileKey: "file",
            fileName: "image.jpg",
            chunkedMode: false,
            mimeType: "image/jpeg"
            uploadOptions.httpMethod = "POST";
                uploadOptions.headers = {
                    Connection:"close"
                };
        };
        $cordovaFileTransfer.upload("api/fileupload/uploadfile", "/images/image.jpg", options).then(function (result) {
            console.log("SUCCESS: " + JSON.stringify(result.response));
        }, function (err) {
            console.log("ERROR: " + JSON.stringify(err));
        }, function (progress) {
            // constant progress updates
        });
    }

})

here is my Api Code

 public void UploadFile()
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                // Get the uploaded image from the Files collection
                var httpPostedFile = HttpContext.Current.Request.Files["file"];

                if (httpPostedFile != null)
                {
                    // Validate the uploaded image(optional)

                    // Get the complete file path
                    var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);

                    // Save the uploaded file to "UploadedFiles" folder
                    httpPostedFile.SaveAs(fileSavePath);
                }
            }
        }

Help required.Any suggestion is welcome. Regards

Upvotes: 2

Views: 6742

Answers (2)

Umar Abbas
Umar Abbas

Reputation: 4161

Finally this simple solution works for me.

UPDATE After Changing the Code in App controller and Webapi Controller Every thing working like a charm and images are start saving on server via API.

Change code I Add these line in App controller Options:

 uploadOptions.httpMethod = "POST";
                    uploadOptions.headers = {
                        Connection:"close"
                    };

And Change this line in WebApi Controller

var httpPostedFile = HttpContext.Current.Request.Files["file"];

Also I enables CORS in API.

Thanks.

Upvotes: 2

Jess Patton
Jess Patton

Reputation: 2486

the app I am building for a company had the same issue and we could not get the file up loader to work, what we did is we just posted the image to our server as a base64 string. Then you can simple pull the string from the database and display it in a div. We used the NgCordova camera and then just pass in the data from the takePhoto function. On android (not ios) devices you can compress the string using lz-string.js. Also on Ios we had to make the images png's. If your app only needs to deal with uploading images this is a easy way to make it work.

$scope.takePhoto = function () {
            $ionicScrollDelegate.scrollTop();
            console.log('fired camera');
            $scope.uploadList = false;
            $ionicPlatform.ready(function() {
                var options = {
                    quality: 100,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    allowEdit: false,
                    encodingType: Camera.EncodingType.PNG,
                    targetWidth: 800,
                    targetHeight: 1100,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };
                $cordovaCamera.getPicture(options).then(function (imageData) {
                    $ionicLoading.show({
                        template: 'Processing Image',
                        duration: 2000
                    });
                    $scope.image = "data:image/png;base64," + imageData;
                    if (ionic.Platform.isAndroid() === true) {
                        $scope.Data.Image = LZString.compressToUTF16($scope.image);
                        $scope.Data.isCompressed = 1;
                    } else {
                        $scope.Data.Image = $scope.image;
                        $scope.Data.isCompressed = 0;
                    }
                    if ($scope.tutorial) {
                        $scope.showAlert("Instructions: Step 3", '<div class="center">Now that you have taken a photo of the POD form, you must upload it to the server. Press the upload doc button in the bottom right of the screen.</div>');
                    }
                    $scope.on('')
                }, function (err) {
                    console.log(err);
                });
            }, false);
        };

 $scope.UploadDoc = function () {
            var req = {
                method: 'POST',
                url: ffService.baseUrlAuth + 'cc/upload',
                headers: {
                    'x-access-token': ffService.token
                },
                data: $scope.Data
            };
            if ($scope.Data.Image === null || $scope.Data.Value === '') {
                $scope.showAlert("Uh Oh!", '<div class="center">Please take a photo of your document before attempting an upload.</div>');
            } else {
                $http(req).success(function (data, status, headers, config) {
                    localStorage.setItem('tutorial', false);
                    $scope.tutorial = false;
                    $scope.getUploads($scope.PODOrder.OrderNo);
                    $scope.showAlert("Success!", '<div class="center">Your Document has been successfully uploaded!</div>');
                    $scope.uploadList = true;
                }).error(function (data, status, headers, config) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.showAlert("Something went wrong!", '<div class="center">Please make sure you have an internet connection and try again.</div>');
                }).then(function(data, status, headers, config){
                    $scope.Data.Image = null;
                });
            }
        };

Upvotes: 3

Related Questions