文件上传处理文件从xhr到web api

时间:2014-02-10 07:10:08

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

我正在使用以下代码将文件上传到服务器,

使用Javascript:

      function FileUpload(ServerName) {
alert("Entering File Change...");

    var file = this.file1[0];
    alert("File Change");
    var xhr = new XMLHttpRequest();
    xhr.file = file; // not necessary if you create scopes like this
    xhr.addEventListener('progress', function(e) {
        alert("progress");

        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xhr.upload ) {
        xhr.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' +   (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xhr.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xhr upload complete', e]);
        }
    };
    xhr.open('post', "http://localhost:49868/UploadFile/" + ServerName, true);
    xhr.send(file);

     }

网络API代码:

       [HttpPost]
       [ActionName("UploadFile")]
       public HttpResponseMessage UploadFile(string servername)
       {  
      try
        {
            HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin",  "*");

            var httpRequest = HttpContext.Current.Request;

            HttpResponseMessage result = null;

            // Check if files are available
            if (httpRequest.Files.Count > 0)
            {
                var files = new List<string>();

                // interate the files and save on the server
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    //var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    postedFile.SaveAs("C:\\Users\\Desktop\\New folder (4)\\" + postedFile.FileName);

                    //files.Add(filePath);
                    //File.Copy(filePath, RootPath + postedFile.FileName);
                    //File.Delete(filePath);
                }

                // return result
                result = Request.CreateResponse(HttpStatusCode.Created, files);
            }
            else
            {
                // return BadRequest (no file(s) available)
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

           return result;

          }

        catch (Exception ex)
        {
            return null;
        }

      }

我的问题是如何在服务器端处理这个问题,即在web api中,如何在服务器上获取文件并将其存储在某个特定位置?

现在httpRequest.Files返回null,在哪里获取文件并保存?

0 个答案:

没有答案