Après chaque postback le contenu du composant FileUpload est perdu si on ne l’exploite pas. Il peut arriver des cas où l’on a besoin de le conserver sans forcément le sauvegarder sur disque.
Pour ces situations, j’utilise un objet SessionHttpPostedFile, reprenant les même possiblités qu’un HttpPostedFile et que j’ai rendu sérializable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
/// <summary>
/// Equivalent Serializable d'un httpPostedFile, permet entre autre son stockage en session
/// </summary>
[Serializable]
public class SessionHttpPostedFile
{
private byte[] BytePostedFile;
[NonSerialized]
private Stream TmpStream;
/// <summary>
/// Constructeur
/// </summary>
public SessionHttpPostedFile()
{
TmpStream = new MemoryStream();
ContentLength = 0;
ContentType = string.Empty;
FileName = string.Empty;
}
/// <summary>
/// Taille du fichier en Byte
/// </summary>
public int ContentLength { get; set; }
/// <summary>
/// Type Mime du fichier
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Nom du fichier
/// </summary>
public string FileName { get; set; }
/// <summary>
/// InputStream du fichier
/// </summary>
public Stream InputStream
{
get
{
if ((TmpStream == null || TmpStream.Length < 1) && BytePostedFile != null)
{
TmpStream = new MemoryStream();
TmpStream.Write(BytePostedFile, 0, BytePostedFile.Length);
}
return TmpStream;
}
set {
TmpStream = value;
BytePostedFile = ReadToEnd(TmpStream);
}
}
/// <summary>
/// Sauvegarde le stream à l'emplacement voulu
/// </summary>
/// <param name="SaveFilename"></param>
public void SaveAs(string SaveFilename)
{
try
{
var f = File.Create(SaveFilename);
f.Close();
File.WriteAllBytes(SaveFilename, BytePostedFile);
}
catch { }
}
/// <summary>
/// Converti un stream en Byte[]
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
private byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0; int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp; totalBytesRead++;
}
}
}
byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer;
}
finally { stream.Position = originalPosition; }
}
}
Aucun commentaire:
Enregistrer un commentaire