没有收到Web api selfhost ajax文件上传xmlhttprequest

时间:2014-02-13 14:23:21

标签: javascript ajax asp.net-web-api xmlhttprequest

我正在关注web api服务器上的http post方法的ajax调用

JavaScript的:

 function FileUpload(WebApiUrl,somedataasparam) {

var files = $("#file1").get(0).files;
if (files.length > 0) {
    if (window.FormData !== undefined) {
        var data = new FormData();
       // TolitoProgressBar('progressbar').setValue(20);
        for (i = 0; i < files.length; i++) {
            data.append("file" + i, files[i]);
        }
    } 
        $.ajax({
            type: "POST",
            url: WebApiUrl + "UploadFile/" + somedataasparam,
            contentType: false,
            processData: false,
            data: data,
            xhrFields: {
               // withCredentials: true,
                // add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
                onprogress: function (progress) {
                    // calculate upload progress
                    var percentage = Math.floor((progress.total / progress.totalSize) * 100);


                    TolitoProgressBar('progressbar').setValue(parseInt(percentage));

                    // log upload progress to console
                    console.log('progress', percentage);
                    if (percentage === 100) {
                        console.log('DONE!');
                    }
                }
            },


            success: function (results) {
                alert("success");
              //  TolitoProgressBar('progressbar').setValue(parseInt(results));
                //alert(results);
                for (i = 0; i < results.length; i++) {

                 //   alert(results[i]);
                }

            }

        });

    } else {
        alert("This browser doesn't support HTML5 multiple file uploads!");
    }
}
控制器中的

方法,

  [HttpPost]
  [ActionName("UploadFile")]
  public async Task<HttpResponseMessage> FileUpload(HttpRequestMessage Request, string somedata)
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        try
        {


            string Path = "C:\\Users\\Desktop\\New folder (4)\\";

            // File.SetAttributes(Path, FileAttributes.Normal);

            var provider = new MultipartFormDataStreamProvider(Path);

            // Read the form data and return an async task.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);

        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

我为自我主持人写了配置

      public class CustomHeaderHandler : DelegatingHandler
{

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {

        return base.SendAsync(request, cancellationToken)
            .ContinueWith((task) =>
            {

                HttpResponseMessage response = task.Result;
                response.Headers.Add("Access-Control-Allow-Origin", "*");
                response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
                response.Headers.Add("Access-Control-Max-Age", "1728000");
                response.Headers.Add("Cache-Control", "no-cache");
                response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                return response;
            });
    }


         var config = new HttpSelfHostConfiguration(strUrl);

        config.MessageHandlers.Add(new CustomHeaderHandler());

客户端中的“ xhr ”未更新,未返回进度值,浏览器控制台中没有错误。我不知道出了什么问题。

0 个答案:

没有答案