首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实例化HttpPostedFile

如何实例化HttpPostedFile
EN

Stack Overflow用户
提问于 2011-04-01 22:23:48
回答 2查看 21K关注 0票数 15

我正在尝试与一个我无法控制的系统进行通信,但是它的一个方法在HttpPostedFile中,在我的代码中,我有一个字节数组。有没有人有一个实例化HttpPostedFile的例子,因为我知道它的构造函数是内部的?

我找到的最好的是使用反射的Creating an instance of HttpPostedFile with Reflection,但是他们被引导到了另一个方向,我不能走这个方向,因为我不能修改第三方系统的方法签名。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-01 22:59:30

这真的是非常繁琐的代码,但是下面的代码对我来说似乎是有效的:

代码语言:javascript
复制
public HttpPostedFile ConstructHttpPostedFile(byte[] data, string filename, string contentType) {
  // Get the System.Web assembly reference
  Assembly systemWebAssembly = typeof (HttpPostedFileBase).Assembly;
  // Get the types of the two internal types we need
  Type typeHttpRawUploadedContent = systemWebAssembly.GetType("System.Web.HttpRawUploadedContent");
  Type typeHttpInputStream = systemWebAssembly.GetType("System.Web.HttpInputStream");

  // Prepare the signatures of the constructors we want.
  Type[] uploadedParams = { typeof(int), typeof(int) };
  Type[] streamParams = {typeHttpRawUploadedContent, typeof (int), typeof (int)};
  Type[] parameters = { typeof(string), typeof(string), typeHttpInputStream };

  // Create an HttpRawUploadedContent instance
  object uploadedContent = typeHttpRawUploadedContent
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, uploadedParams, null)
    .Invoke(new object[]{data.Length, data.Length});

  // Call the AddBytes method
  typeHttpRawUploadedContent
    .GetMethod("AddBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, new object[] {data, 0, data.Length});

  // This is necessary if you will be using the returned content (ie to Save)
  typeHttpRawUploadedContent
    .GetMethod("DoneAddingBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, null);

  // Create an HttpInputStream instance
  object stream = (Stream)typeHttpInputStream
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, streamParams, null)
    .Invoke(new object[] {uploadedContent, 0, data.Length});

  // Create an HttpPostedFile instance
  HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null)
    .Invoke(new object[] {filename, contentType, stream});

  return postedFile;
}
票数 26
EN

Stack Overflow用户

发布于 2011-04-01 22:39:35

你可以试试

代码语言:javascript
复制
 var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
 var obj = (HttpPostedFile)constructorInfo
           .Invoke(new object[] { "filename", "image/jpeg", null });

obj的类型为HttpPostedFile。我正在将最后一个参数设置为HttpInputStream,但它必须是null。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5514715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档