Reputation:
Is it possible to convert a byte[] to a HttpPostedFile?
System.Web.HttpPostedFile objFile = fileData;
where fileData is a byte array of an image, gives a "can not be implicitly converted error".
Upvotes: 1
Views: 7365
Reputation: 686
Try this ,worked for me
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;
}
Upvotes: 0
Reputation: 4297
If you look at the source for the class you'll see a few things.
internal
, so you'll never directly construct an instance.sealed
, so you can't add your own constructor using inheritance.Instead of trying to convert a byte array into an instance of HttpPostedFile
, you'll have a much smoother experience by converting your downstream methods to accept byte[]
as input, or maybe Stream
. If you need the other properties of HttpPostedFile
, then you could just send them in directly as additional parameters, or write your own class to wrap them up.
Upvotes: 7