angularJS 在edge浏览器上传文件,没法主动触发ng-click WebAPI Angularjs 上传文件

今天发现的问题

在谷歌浏览器一直运行良好的功能,在edge浏览器不能使用。html

代码参考个人另一篇博客:WebAPI Angularjs 上传文件git

不能运行的缘由

下图红框中的代码在edge浏览器中没法执行,也就不能执行下面的上传文件代码。github

解决方案

既然缘由找到了,就能够寻找解决方案了,找了一下午,有一篇有用的文章:angular ng-click程序触发,方法web

个人解决方案(注意加粗加大的代码【关键哟】)

JS代码以下:

define(['app'], function (app) {
      app.controller('editController', ['$scope', "$http", 'webConfig', function ($scope, $http, webConfig) {
        $scope.save = function () {
            var fd = new FormData();
            var file = document.querySelector('input[type=file]').files[0];
            fd.append('logo', file); //angular 上传的文件必须使用特殊的格式处理,不是json格式
            $http({
                method: 'POST',
                url: webConfig.apiRoot + "/api/ECategoryDetail/PostFiles", //"https://localhost:44320//api/ECategoryDetail/PostFiles"
                data: fd,
                headers: { 'Content-Type': undefined }, // 写成是undifined,浏览器才自动转化为 文件上传的类型
                transformRequest: angular.identity
            }).success(function (response) {
                //上传成功的操做
                if (response.mark) //接口返回的数据标志位,是否保存成功,保存成功则把文件相对地址更新到实体中
                    $scope.editdata.SourceURL = response.result;
                else
                    alert("上传失败");
            });
        };
    }]);

})

function coverChange() {
    $('#uploads').click();
    angular.element($('#uploads')).click();// ok
};

你们看到这个代码会不会觉得我写错了,这个coverChange方法就要写到define外面,否则页面中没法调用到这个方法,会提示undefined function。json

HTML代码:

<div id="preview">
  <img src="{{csInfo.CS.CoverUrl}}" ng-disabled="uploadimg" id="txtSourceURL" name="txtSourceURL" style="width: 180px; cursor: pointer; height: 70px;" onclick="$('#fileUpload').click()" />
  <input id="fileUpload" type="file" accept="image/jpg,image/jpeg,image/png, image/bmp" name="fileUpload" onchange="coverChange()" style="display: none;" /> 
  <button ng-click="save()" id="uploads" style="display: none;">肯定上传</button> <!--必须使用其余控件(按钮或者标签)调用上传(save())方法-->
  <input id="inputSourceURL" name="inputSourceURL" type="hidden" ng-model="csInfo.CS.CoverUrl" required />
</div>

<div class="word"> 支持.jpg .png .jpeg 格式<span id="loading" ng-show="uploadimg"><img src="/libs/source/images/loading.gif" alt="">正在上传,请稍后···</span> </div>

API接口代码

作了一点小改动,由于edge浏览器传过来的filename是一个带盘符的路径(C:\\xxx\\filename.ext)api

var file = HttpContext.Current.Request.Files["cover"];
var fileName = file.FileName;
var fn = fileName.Split('\\');
if (fn.Length > 1)
{
     fileName = fn[fn.Length - 1];
}
var fs = fileName.Split('.');
if (fs.Length > 1)
{
    var ext = fs[fs.Length - 1];
}

 

就是对文件名单独处理一下便可,剩下的接口代码同样。浏览器

这样改动之后就能够在谷歌和edge浏览器下运行了。app

相关文章
相关标签/搜索