1

因此,当我将文件发送到 MVC 控制器时,此 Kendo UI Upload 运行良好,但我必须更改它并将文件直接发送到 API 控制器,但它失败了。

这是剑道上传的初始化代码:

$("#files").kendoUpload({
  async: {
    saveUrl: "@WebApiHelper.GetUrl("Notification/UploadFile")",
    removeUrl: "remove",
    autoUpload: true
  },
  success: function(),
  error: function()
}

在 Chrome 控制台上,它显示Load Canceled在网络选项卡中请求的状态文本中:

在此处输入图像描述

请求的结果如下图所示:

Request URL:http://localhost:45706/api/Notification/UploadFile
Request Method:OPTIONS
Status Code:200 Ok

Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:origin, content-type
Access-Control-Request-Method:POST
Host:localhost:45706
Origin:http://localhost:1654
Proxy-Connection:keep-alive
Referer:http://localhost:1654/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, accept, content-type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
allow-access-from domain:*
Cache-Control:no-cache
Content-Length:0
Date:Fri, 03 May 2013 16:53:30 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcR0F0ZWNcRG9jdW1lbnRzXEdBdGVjXE9kaXNzZWlhXEFwcGxpY2F0aW9uXEdBdGVjLkFncm9XZWIuQ29yZVxHQXRlYy5BZ3JvV2ViLkNvcmUuQVBJXGFwaVxOb3RpZmljYXRpb25cVXBsb2FkRmlsZQ==?=

请注意,状态码是 200,因为我在方法中返回了它。所以它到达API方法......

[HttpPost][HttpOptions]
public HttpResponseMessage UploadFile(HttpPostedFileBase files)

...但files参数是 aways null

这是 API webconfig 文件中与 CORS 相关的属性:

<httpProtocol>   
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="allow-access-from domain" value="*" />
    <add name="Access-Control-Allow-Headers" value="origin, accept, content-type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />  
  </customHeaders> 
</httpProtocol>

有什么想法吗 ?任何帮助将不胜感激!

4

1 回答 1

0

这段代码对我有用。

public ActionResult Document_Create([DataSourceRequest] DataSourceRequest request, Customer obj, IEnumerable<HttpPostedFileBase> Docs)
        {
                    foreach (var Doc in Docs)
                    {
                        string newFileName = Path.GetFileName(Doc.FileName).Replace(" ",""); //Guid.NewGuid().ToString() + Path.GetExtension(Doc.FileName);
                        var physicalPath = Path.Combine(Server.MapPath("~/Documents/"), newFileName);
                        Doc.SaveAs(physicalPath);

                    }
            return Json(new[] { obj }.ToDataSourceResult(request, ModelState));
        }
于 2013-05-03T18:49:48.547 回答