我試圖保存在我的D:目錄中的圖像,並完成此操作,我保存在Session
我的FileUpload
組件的一些信息。文件通過流保存,但無法打開
在我的方法稱爲btnConfirm_Click
創建我Session
,在我btnSave_Click
方法我恢復此信息並嘗試保存文件,但是當我在D:
目錄查詢,該文件存在,但是當我打開這個文件,我看到了該消息:The windows photo viewer can not open this picture because the file appears to be damaged, corrupted, or is too big ..
有人可以幫助我嗎?
C#代碼
protected void btnConfirm_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string sFileName = FileUpload1.FileName;
string fileExtension = System.IO.Path.GetExtension(sFileName).ToLower();
foreach (string ext in new string[] { ".jpeg", ".jpg", ".png" })
{
if (fileExtension == ext)
{
Session["Document"] = sFileName + fileExtension;
Session["Byte"] = FileUpload1.FileBytes;
Session["Content"] = FileUpload1.FileContent;
byte[] b = (byte[])Session["Byte"];
}
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Session["Document"].ToString() != null)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(Session["Content"].ToString());
MemoryStream stream = new MemoryStream(byteArray);
sPath = "D:/123.jpg";
FileStream fileStream = File.Create(sPath, (int)stream.Length);
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
catch
{
}
}
}
和會話[「內容」]是一個流,而不是字節數組 –
@JeffFoster謝謝!有用。 –