如何将Request对象转换为HttpPostedFileBase类型. [英] How to convert Request object to HttpPostedFileBase type.

查看:258
本文介绍了如何将Request对象转换为HttpPostedFileBase类型.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在将带有html文件api的文件发送到控制器...
像..

In my application i am sending file with html file api to controller...
like..

xhr.setRequestHeader("Cache-Control", "no-cache");
                         xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                         xhr.setRequestHeader("Content-Type", "multipart/form-data");
                         xhr.setRequestHeader("X-File-Name", file.fileName);
                         xhr.setRequestHeader("X-File-Size", file.fileSize);
                         xhr.setRequestHeader("X-File-Type", file.type);
                        xhr.setRequestHeader("X-File", file);

                         // Send the file (doh)
                         xhr.send(file);


控制器端是


and controller side is

[HttpPost]
        public JsonResult Upload(object fileToUpload1)
        {
 var fileName = Request.Headers["X-File-Name"];
            var fileSize = Request.Headers["X-File-Size"];
            var fileType = Request.Headers["X-File-Type"];
            //var x = DateTime.Now.Second;
            //var y = x + 20;
            //if((y-x)>x)
            if (fileName != null)
            {
                
                Request.SaveAs("D:\\uploadimage\\" + fileName, false);
}
  return Json(true, JsonRequestBehavior.AllowGet);
}


它工作正常...但是我想将该对象转换为HttpPostedFileBase类型,因此我可以将其传递给参数类型为HttpPostedFileBase类型的方法.


It works fine...but i want to cast that object to HttpPostedFileBase type so i can pass to method whose parameter is of type HttpPostedFileBase..I try like below but it gives null value..

HttpPostedFileBase hpf = Request.Files["fileToUpload1"];

推荐答案


如果有帮助,请尝试以下操作:


Try this if could help:

try
 {
      Byte[] imgByte = null;
      // Cast object to FileUpload
      FileUpload img = (FileUpload)Upload(fileToUpload1)

      if (img.HasFile && img.PostedFile != null)
      {
          //Create a PostedFile
          HttpPostedFile file = img.PostedFile;
          //Create byte Array with file len
          imgByte = new Byte[file.ContentLength];
          //force the control to load data in array
          file.InputStream.Read(imgByte, 0, file.ContentLength);
          originalSize = file.ContentLength;
      }
  }
  catch
  {
  }
}



请别忘了投票,如果有帮助的话,以便其他人可以考虑作为答案...

问候



Please do not forget to vote if could help so that others may consider as answer...

Regards,


这篇关于如何将Request对象转换为HttpPostedFileBase类型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆