tobbbe
7/7/2016 - 8:18 AM

web api, umbraco, fileupload

web api, umbraco, fileupload

(function () {
    angular.module('toxic', ['ngFileUpload']).directive('fileUploader', fileUploader);

    var template = window.FormData ? [
            '<button id="fileuploader" class="file-picker-btn" ngf-select="vm.fileAdded($files, $invalidFiles)" type="file" ng-model="vm.files" ngf-multiple="true" ngf-max-size="250MB" ngf-pattern="\'image/*\'" ngf-accept="\'image/*\'">Välj filer</button>',
            '<div ng-repeat="file in vm.files">{{file.name}}</div>',
            //'<button ng-disabled="!vm.files.length || vm.isUploading" ng-click="vm.startUpload()">Ladda upp</button>'
    ].join('') : 'Din webbläsare är tyvärr för gammal för att ladda upp filer.'

    fileUploader.$inject = ['Upload', '$timeout'];
    function fileUploader(Upload, $timeout) {
        return {
            controller: ctrl,
            controllerAs: 'vm',
            restrict: 'E',
            scope: {},
            template: template
        }

        function ctrl() {
            var vm = this;
            vm.fileAdded = fileAdded;
            vm.startUpload = startUpload;
            vm.isUploading = false;

            function fileAdded(files, invalidFiles) {
                for (var i in invalidFiles) {
                    alert("Filen har inte rätt format: " + invalidFiles[i].name)
                }
            }

            function startUpload() {
                if (!vm.isUploading && vm.files && vm.files.length) {
                    vm.isUploading = true;
                    
                    var promise = Upload.upload({
                        url: '/umbraco/api/fileuploader/upload?orderid=' + "test",
                        data: vm.files
                    })
                    promise.then(function (response) {
                        //$timeout(function () {
                        //    console.log('Uppladdat');
                        //});
                    }, function (response) {
                        //if (response.status > 0) {
                        //    console.log(response.data);
                        //}
                    }, function (evt) {
                        //console.log(Math.min(100, parseInt(100.0 * evt.loaded / evt.total)));
                    })
                    .finally(function () {
                        vm.isUploading = false;
                    })

                    return promise;
                }
            }
        }
    }
    
})()
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
using System.Net.Http.Headers;

namespace Minnesgrossisten.Extra
{
    public class FileUploaderController : UmbracoApiController
    {
        [HttpPost]
        public async Task<IHttpActionResult> Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return BadRequest("Unsupported media type");
            }

            var rootFolderPath = HttpContext.Current.Server.MapPath("~/CustomerUploads/");

            if (!Directory.Exists(rootFolderPath))
            {
                Directory.CreateDirectory(rootFolderPath);
            }

            var orderUploadsFolder = rootFolderPath + Request.GetQueryNameValuePairs().FirstOrDefault(qs => qs.Key == "orderid").Value;
            if (!Directory.Exists(orderUploadsFolder))
            {
                Directory.CreateDirectory(orderUploadsFolder);
            }

            try
            {
                var provider = new CustomMultipartFormDataStreamProvider(orderUploadsFolder);
                var result = await Request.Content.ReadAsMultipartAsync(provider);

                if (!provider.Contents.Any())
                {
                    return BadRequest("No files");
                }

                //var something = result.FormData["something"]; // get something from 

                var listOfUploadedFileUrls = new List<string>();
                foreach (var f in provider.Contents)
                {
                    listOfUploadedFileUrls.Add(orderUploadsFolder + f.Headers.ContentDisposition.FileName.Trim('\"'));
                    //await f.ReadAsByteArrayAsync();
                }

                return Ok(listOfUploadedFileUrls);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.GetBaseException().Message);
            }
            
        }
    }

    // save files with real filename ---> http://stackoverflow.com/questions/10970750/asp-net-web-api-file-saved-as-bodypart-3ded2bfb-40be-4183-b789-9301f93e90af
    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string rootPath) : base(rootPath)
        {
        }

        public CustomMultipartFormDataStreamProvider(string rootPath, int bufferSize) : base(rootPath, bufferSize)
        {
        }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            //Make the file name URL safe and then use it & is the only disallowed url character allowed in a windows filename
            var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName)
              ? headers.ContentDisposition.FileName
              : "NoName";
            return name.Trim('"').Replace("&", "and");
        }
    }
}