错误404:请上传图片 - AngularJs

时间:2017-01-18 06:26:05

标签: angularjs

我正在尝试上传Angular Js中的文件。我正在关注@georgeawg在https://plnkr.co/edit/CqIixHWefjYmDfmJPbNF?p=preview

中提供的以下示例Pass file reader data to service in Angular Js

在index.cshtml中

 <input type="file" my-files="files" />
 <input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />

在controller.js

angular.module('testApp.controllers', []).
controller('testApp.Controller', function ($scope, testAPIService, Excel, $timeout, $window, $location, $anchorScroll, $http, sharedDataService) {

var url = "https://siteUrl/UploadImage/";

   var config = {
        headers: {
            "Content-Type": undefined,
        }
    };



$scope.uploadFiles = function () {

 var file = sharedDataService.shared.files[0];

testAPIService.postUploadImage(file).success(function (response) {
       alert(respone)
    });        };   

});

angular.module("testApp.Controller").directive("myFiles", function ($parse, sharedDataService) {
    return function linkFn(scope, elem, attrs) {
        elem.on("change", function (e) {
            alert("hi");
            scope.$eval(attrs.myFiles + "=$files", { $files: e.target.files });

            scope.$apply();        
            sharedDataService.shared = scope;
        });
    };
});

angular.module("testApp.Controller").directive("xdHref", function () {
    return function linkFn(scope, elem, attrs) {
        scope.$watch(attrs.xdHref, function (newVal) {
            newVal && elem.attr("href", newVal);
        });
    };
});

//在service.js

testAPIService.postUploadImage = function (file) {
        var config = {
            headers: {
                "Content-Type": undefined,
            }
        };
        var url = urlBase + 'UploadImage';
        $http.post(url, file, config).
         then(function (response) {
             alert(response.data.data);
         }).catch(function (response) {
             alert( "ERROR " + response.status);
         });

在C#API代码中:

[HttpPost]
        [Route("tests/UploadImage")]
        public async Task<HttpResponseMessage> UploadImage()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            try
            {

                var httpRequest = HttpContext.Current.Request;

                foreach (string file in httpRequest.Files)
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                    var postedFile = httpRequest.Files[file];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {

                        int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  

                        IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png", "jpeg" };
                        var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var filenameOrigin = postedFile.FileName.Substring(0, postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
                            var message = string.Format("Please Upload image of type .jpg,.gif,.png,.jpeg.");

                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {
                            var message = string.Format("Please Upload a file upto 2 mb.");

                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else
                        {

                            string filename = String.Format(@"{0}_{1}_{2}{3}", filenameOrigin, Guid.NewGuid(), DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"), extension);
                            var filePath = HostingEnvironment.MapPath("~/Images/" + filename);

                            postedFile.SaveAs(filePath);
                            if (!String.IsNullOrEmpty(filePath))
                            {
                                dict.Add("filePath", filePath);
                            }
                        }
                    }

                    var messageSuccess = string.Format("Image Updated Successfully.");
                    dict.Add("Success", messageSuccess);
                    return Request.CreateResponse(HttpStatusCode.Created, dict);
                }
                var res = string.Format("Please Upload a image.");
                dict.Add("error", res);
                return Request.CreateResponse(HttpStatusCode.NotFound, dict);
            }
            catch (Exception ex)
            {
                var res = string.Format("something went wrong");
                dict.Add("error", res);
                return Request.CreateResponse(HttpStatusCode.NotFound, dict);
            }
        }

在var文件中,我获取上传的文件名,大小,图像类型。在下一行$ http.post中,调用被移动到catch,我收到错误:404 - 请上传图片 错过了什么?如何解决这个问题? 感谢

0 个答案:

没有答案