簡體   English   中英

在AngularJs中上傳文件-錯誤:XMLHttpRequest無法加載URL-狀態:-1

[英]File Upload in AngularJs - Error: XMLHttpRequest cannot load URL - status: -1

我正在嘗試使用Jive中的AngularJs做文件上傳選項。 我正在嘗試以下代碼,但出現以下錯誤:

OPTIONS https://test.com/MyApp/api/Seasons/UploadImage 405 (Method Not Allowed)

XMLHttpRequest cannot load https://test.com/MyApp/api/Seasons/UploadImage. Response for preflight has invalid HTTP status code 405

status: -1
StatusText: ""

以下是我嘗試過的代碼:

//Index.html

<input type="file" class="form-control" id="imageUploadfile" my-files="files" name="Imagefile" accept="image/*" />
<input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />

//controller.js

$scope.uploadFiles = function () {

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

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

    var url = _testBaseUrl + 'api/Seasons/UploadImage';


   $http.post(url, file, config).

         then(function (response) {
             $scope.result = "SUCCESS";

           $scope.data = response.data.data;
         }).catch(function (response) {
             alert( "ERROR " + response.status);
         });
    };

我沒有在web.config中添加端點。 以下是web.config中的處理程序配置

 <handlers accessPolicy="Read, Script">
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"
         path="*."
         verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
         modules="IsapiModule"
         scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
         preCondition="classicMode,runtimeVersionv4.0,bitness64"
         responseBufferLimit="0" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

在網絡api方法中:

[HttpPost]
        [Route("Seasons/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);
            }
        }

這是一個跨域調用。 如何解決這個問題? 謝謝

檢查Web服務的內容類型,或嘗試通過在標頭中添加內容類型multipart / form-data而不是未定義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM