2011年1月20日 星期四

ListView 搭配資料庫中的圖片

1. 在ListView中放置顯示圖片及上傳圖片的控制項,圖片網址為一泛行處理常式
<asp:Image ID="picAlbum" runat="server" ImageUrl='<%# "ShowImage.ashx?id=" + Eval("id") %>' />
<asp:FileUpload ID="imgUpload" runat="server" />

2. 撰寫泛行處理常式顯示資料庫中的圖片欄位
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id;
if (context.Request.QueryString["id"] != null)
id = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = GetImage(id);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

private Stream GetImage(int id)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT 照片 FROM 照片表格 WHERE ID = @ID";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", id);
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
}
}
}

public bool IsReusable
{
get
{
return false;
}
}
}

3. 於datasource的inserting、updating事件函數中取得使用者選擇的檔案作為參數值
private Byte[] getImage(FileUpload img)
{
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To 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);
}
return imgByte;
}

4. 針對updating或inserting事件必須考慮使用者未選取任何檔案時會遇到資料型別不符問題,因為null會當作nvarchar型態造成語法錯誤問題,所以必須抽換參數改用SqlParameter並指定型別為Image,因為原本的參數型別不包含image
e.Command.Parameters.Remove(e.Command.Parameters["@照片"]);
e.Command.Parameters.Add(new SqlParameter("@照片", System.Data.SqlDbType.Image));

沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...