Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Adriano Fabri 459 posts 1602 karma points
    Oct 05, 2018 @ 15:41
    Adriano Fabri
    0

    File Upload problems in backoffice custom section

    Hi, I'm trying to realize a file upload action in my custom package, but it doesn't work.

    I have a custom section with a custom tree. The first voice of the tree will allow users to upload an image in a custom directory in "~/Media" directory on file system

    Below I show my view, controller, resource and c# code.

    Can anyone help me to understand where is the problem and how to solve it?

    Thank you

    Adriano


    The View:

    (No problem on rendering file upload fields)

        <div class="file-uploader">
            <label for="vm.bkgImage">Select an image</label>
            <input type="file" id="vm.bkgImage" name="file" ng-model="vm.bkgImage" onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/jpg, image/png" />
             <button class="btn publish" ng-click="vm.addBkgImage(vm.bkgImage)">Upload</button>
        </div>
    

    The Controller:

    (No problems on file selection)

        vm.bkgImage = [];
        var allFiles = [];
        var file = [];
    
        $scope.LoadFileData = function (files) {
            file = files[0];
            allFiles = files;
        };
    
        vm.addBkgImage = function (bkgImage) {
            afclpResource.postUploadImage(file, allFiles).then(function (response) {
                if (response.data !== "null") {
                    notificationsService.add(vm.uploadSuccessNotification);
                }
                else {
                    notificationsService.add(vm.uploadErrorNotification);
                    vm.showDeletePanel = false;
                }
            });
        };
    

    The Resource

    (Here I receive a "500 - Internal Server Error" after click the "upload" button. The action stops and don't reach c# code)

        postUploadImage: function (file, allFiles) {
            return $http({
                method: "POST",
                url: 'AFCLP/AFCLPResourceApi/PostAFCLPUploadImage',
                headers: { "Content-Type": "undefined" },
                transformRequest: function (data) {
                    var formData = new FormData();
                    formData.append("file", angular.toJson(file.name));
                    for (var i = 0; i < allFiles.length; i++) {
                        formData.append("files[" + i + "]", allFiles[i]);
                    }
                    console.log(formData);
                    console.log(data);
                    return formData;
                },
                data: { file, allFiles }
            });
        }
    

    The C# method

        /// <summary>
        /// Post - Upload Image
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public bool PostAFCLPUploadImage(HttpPostedFileBase file, HttpPostedFileBase[] files)
        {
            string afclpMediaPath = HttpContext.Current.Server.MapPath(SystemDirectories.Media + "/AFCLP/backgrounds");
    
            try
            {
                // HERE WILL BE THE UPLOAD CODE
    
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error<Exception>(ex.Message, ex);
    
                return false;
            }
        }
    
  • Adriano Fabri 459 posts 1602 karma points
    Oct 08, 2018 @ 08:11
    Adriano Fabri
    0

    Watching the header, when start upload, I receive this exception message:

    No MediaTypeFormatter is available to read an object of type 'HttpPostedFile' with media type "multipart/form-data"

    Any Idea? :-o

  • Adriano Fabri 459 posts 1602 karma points
    Oct 08, 2018 @ 15:33
    Adriano Fabri
    0

    I tried to modify the code as below and finally I arrive on my POST method. The problem now is that for some reason the request.FileData is empty

    Anyone can help me?


    The View:

    <div class="file-uploader">
        <form id="afclpUploadForm" name="afclpUploadForm" role="form" class="form-inline">
            <label for="file">Select an image</label>
            <input type="file" ng-model="picFile" name="file" ngf-change="fileSelected(this)" ngf-accept="'image/jpg, image/png'" />
            <button ng-click="saveBkgImage(picFile)" class="btn publish">Upload</button>
        </form>
    </div>
    

    The Controller:

    $scope.picFile = [];
    $scope.files = [];
    
    $scope.fileSelected = function (element) {
        //add the file object to the scope's files collection
        $scope.files.push(element.picFile);
    };
    
    //the save method
    $scope.saveBkgImage = function (picFile) {
        afclpResource.postUploadImage($scope, picFile).then(function (response) {
            if (response.data !== "null") {
                notificationsService.add($scope.uploadSuccessNotification);
            }
            else {
                notificationsService.add($scope.uploadErrorNotification);
                $scope.showDeletePanel = false;
            }
        });
    };
    

    The Resource

    postUploadImage: function (file, allFiles) {
        return $http({
            method: "POST",
            url: 'AFCLP/AFCLPResourceApi/PostAFCLPUploadImage',
            headers: { 'Content-Type': undefined },
            transformRequest: function (data) {
                var formData = new FormData();
                formData.append("model", angular.toJson(data.model));
                for (var i = 0; i < data.files.lenght; i++) {
                    formData.append("file" + i, data.files[i]);
                }
    
                return formData;
            },
            data: { model: model, files: file }
        });
    }
    

    The C# method

    /// <summary>
    /// Post - Upload Image
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<HttpResponseMessage> PostAFCLPUploadImage()
    {
        try
        {
            // Save File
            if (!Request.Content.IsMimeMultipartContent())
            {
                LogHelper.Error<HttpResponseException>(HttpStatusCode.UnsupportedMediaType.ToString(), new HttpResponseException(HttpStatusCode.UnsupportedMediaType));
                return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, new HttpResponseException(HttpStatusCode.UnsupportedMediaType));
            }
    
            //Directory.CreateDirectory(afclpMediaPath);
            var provider = new MultipartFormDataStreamProvider(afclpMediaPath);
            var result = await Request.Content.ReadAsMultipartAsync(provider);
    
            if (result.FormData["model"] == null)
            {
                LogHelper.Error<HttpResponseException>(HttpStatusCode.BadRequest.ToString(), new HttpResponseException(HttpStatusCode.BadRequest));
                return Request.CreateResponse(HttpStatusCode.BadRequest, new HttpResponseException(HttpStatusCode.BadRequest));
            }
    
            var model = result.FormData["model"];
    
            if (result.FileData.Count() > 0)
            {
                //Get the files
                foreach (var file in result.FileData)
                {
                    //Save each uploaded file
    
                }
            }
    
            return Request.CreateResponse(HttpStatusCode.OK, "Success!");
    
            //LogHelper.Error<HttpResponseException>("Error! (" + HttpStatusCode.InternalServerError + ") FileData Empty", new HttpResponseException(HttpStatusCode.InternalServerError));
            //throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, "Error! FileData Empty"));
        }
        catch (HttpResponseException ex)
        {
            LogHelper.Error<HttpResponseException>("Error! (" + HttpStatusCode.InternalServerError + ") " + ex.Message, ex);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }
    
  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Oct 24, 2019 @ 17:47
    Alex Skrypnyk
    0

    Hi Adriano,

    Did you solve this issue? Can you share with our community?

    Alex

  • Morten Christensen 61 posts 215 karma points
    Oct 28, 2019 @ 15:05
  • Adriano Fabri 459 posts 1602 karma points
    Nov 06, 2019 @ 14:25
    Adriano Fabri
    0

    Sorry for delay. I used a method similar to that you can find in the article indicated by Morten

Please Sign in or register to post replies

Write your reply to:

Draft