tobbbe
3/29/2016 - 12:51 PM

umbraco web api file import (to use with ng-file-upload)

umbraco web api file import (to use with ng-file-upload)

angular.module('elskylt').directive('fileUploader', fileUploader);

function fileUploader(Upload, $timeout, $rootScope) {
    var directive = {
        link: link,
        restrict: 'E',
        scope: {},
        template: [
            '<div ng-show="isUploading">Importerar ({{uploadProgress}}%)</div>',
            '<div ng-hide="isUploading">',
                '<button type="file" ng-model="file" ngf-accept="\'.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel\'" ngf-multiple="false" ngf-max-size="20MB" ngf-pattern="\'.xls, .xlsx, .csv\'" ngf-select="fileAdded($files, $invalidFiles)">Välj fil</button>&nbsp;',
                '<span ng-bind="selectedFileName"></span>',
                '<br><button ng-show="selectedFileName.length" type="button" ng-click="uploadFile($file, $invalidFiles)">Importera</button>',
            '</div>'
        ].join('')
    };

    return directive;

    function link(scope, element, attrs) {

        scope.fileAdded = function (validFiles, invalidFiles) {
            if (invalidFiles.length) {
                scope.selectedFileName = "";
                alert("File must be .csv, .xls or .xlsx")
            }
            else if (validFiles.length) {
                scope.selectedFileName = validFiles[0].name;
            }
            else {
                scope.selectedFileName = "";
            }
        }

        scope.uploadFile = function () {
            scope.isUploading = true;
            scope.uploadProgress = 0;

            if (scope.file) {
                Upload.upload({
                    url: 'http://localhost:57817/umbraco/api/convertexcel/upload',
                    data: { file: scope.file }
                })
                .then(function (response) {
                    // do stuff on success                  
                }, function (response) {
                    // error
                }, function (evt) {
                    // progress
                    scope.uploadProgress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total)) - 1;
                })
            }
        }

    }
}
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 System.Web.Http.Cors;
using Umbraco.Web.WebApi;

namespace Apa.App
{
    [EnableCors("*", "*", "*")]
    public class ConvertExcelController : UmbracoApiController
    {
        public ConvertExcelController()
        {
            GlobalConfiguration.Configuration.Formatters.Clear();
            GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); // make controller always return JSON (chrome asks for xml ex)
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; // intend response in chrome etc
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // make response camelcase
        }

        [HttpPost]
        public async Task<HttpResponseMessage> Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // Save file to disk.
            //var root = HttpContext.Current.Server.MapPath("~/App_Data/Temp/FileUploads");
            //Directory.CreateDirectory(root);
            //var provider = new MultipartFormDataStreamProvider(root);
            //var result = await Request.Content.ReadAsMultipartAsync(provider);

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);
            
            if (!provider.Contents.Any())
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, "No files");
            }

            // if multiple files
            //foreach (var file in provider.Contents)
            //{
            //    var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            //    var buffer = await file.ReadAsByteArrayAsync();
            //    return Request.CreateResponse(HttpStatusCode.OK, filename);
            //}

            var file = provider.Contents.First();

            return Request.CreateResponse(HttpStatusCode.OK, file.Headers.ContentDisposition.FileName);
        }
    }
}
Requeires ng-file-upload https://github.com/danialfarid/ng-file-upload/
Dont forgett to inject into app module 'ngFileUpload'

Use in template: <file-uploader></file-uploader>