文件对象根据要求为空

时间:2019-08-14 18:19:52

标签: asp.net xmlhttprequest

我有前端代码可以上传图片。我有后端代码来接收图像。当请求到达后端时,请求中的Files对象为空。

前端

const xhr = this.xhr = new XMLHttpRequest();
xhr.open( 'POST', this.url, true );
xhr.responseType = 'json';
const data = new FormData();
data.append( 'file', this.loader.file );
this.xhr.send( data );

后端

[HttpPost]
public HttpResponseMessage ImageUpload()
 {
     HttpResponseMessage hrm = Request.CreateResponse(HttpStatusCode.Forbidden, "Image Upload Failed");
     try
      {
         var httpContext = HttpContext.Current.Request;
         string basePath = FileUploadHelpers.GetBasePath();
         if(httpContext.Files.Count > 0)
         {
              HttpPostedFile postedFile = httpContext.Files[0];
              var fileExtension = Path.GetExtension(postedFile.FileName);
              fileExtension = fileExtension == ".jpeg" ? ".jpg" : fileExtension;
              var hashName = FileUploadHelpers.GenerateFilenameHash(DateTime.Now.Ticks);
              var filePath = basePath + "/data/images/" + hashName + fileExtension;
              postedFile.SaveAs(filePath);
              hrm = Request.CreateResponse(HttpStatusCode.OK, filePath);
         }
         else
         {
              hrm = Request.CreateResponse(HttpStatusCode.OK, "No files sent");
         }
      }
      catch (Exception ex)
      {
         Log.LogError(ex, "ImageUpload()");
      }

      return hrm;
}

我希望httpContext对象具有一个名为Files的变量,其中包含File。相反,那里没有文件。

0 个答案:

没有答案