首页 > 解决方案 > 上传excel文件webapi和angularjs和ajax调用

问题描述

我有以下代码我想上传 excel 文件并保存到服务器。但是这个功能不起作用它告诉我 500 (Internal Server Error)我的代码有什么问题请帮助我这个任何专业人士我花了 3 个小时但没有成功。我是谷歌但不是成功简单我想通过 angularjs 或 ajax 调用上传文件

C# 代码不从 AJAX 调用我认为这就是它显示错误的原因

HTML

  <input type="file" id="uploadInput" />
 <button ng-click="SubmitForm()" class="btn btn-info">Submit</button>



 AppModel.controller('ImportExcelCtrl', ['$scope', '$filter', '$http', function ($scope, $filter, $http) {
        $scope.SubmitForm = function () {
            var element = document.getElementById("uploadInput");
            var file = element.files[0];
            console.log(file.name);
            console.log(file);
            var loFormData = new FormData();
            loFormData.append("filename", file.name);
            loFormData.append("file", file);

            var loAjaxRequest = $.ajax({
                cache: false,
                type: 'POST',
                url: "/api/myapi/UploadFileExcel",
                contentType: false,
                processData: false,
                data: loFormData,
                headers: {
                    'Content-Type': 'multipart/form-data'
            }
            });

            loAjaxRequest.done(function (xhr, textStatus) {
                alert(textStatus);
            });
        };
    }]);

CS

[HttpPost]
        public async Task<HttpResponseMessage> UploadFileExcel()
        {
            if (!this.Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            try
            {
                var loProvider = new MultipartFormDataStreamProvider(Path.GetTempPath());

                await Request.Content.ReadAsMultipartAsync(loProvider);

                string lsFilename = loProvider.FormData.GetValues("filename").First();
                var loFile = loProvider.FileData.First();
                string lsFileContent = File.ReadAllText(loFile.LocalFileName);

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (Exception exp)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
        }

标签: jqueryangularjsajaxasp.net-mvc-4asp.net-web-api

解决方案


推荐阅读