上傳圖片的相對路徑到資料庫教程中相應欄位裡,讀取顯示時,將控制項(假設用的是image控制項)的imageurl屬性指向該相對路徑即可。
code:
protected void button1_click(object sender, eventargs e)
{
string name = fileupload1.filename;//擷取檔案名稱
string type = name.substring(name.lastindexof(".") + 1);
//擷取檔案類型
string ipath = server.mappath("image") + "" + name;
//擷取檔案路徑
string wpath = "image" + name;
//[color=red]設定檔案儲存相對路徑
(這裡的路徑起始就是我們存放圖片的檔案夾名)[/color]
string query1 = "insert into images values
('" + wpath + "')";
if (type == "jpg" || type == "gif" ||
type == "bmp" || type == "png")
{
fileupload1.saveas(ipath); //伺服器儲存路徑
sqlhelper.execternonquery(query1);
}
}
顯示按鈕事件:
code:
protected void button2_click(object sender, eventargs e)
{
string query2 = "select * from images where
image_id=" + convert.toint32(textbox1.text);
sqldatareader sdr = sqlhelper.getreader(query2);
string wpath2 = "";
while (sdr.read())
{
wpath2 = sdr[1].tostring();
//獲得相對路徑
}
sdr.close();
image1.imageurl = wpath2;
//圖片顯示路徑就是相對路徑
label1.text = wpath2; //顯示相對路徑
}
下面看另一個執行個體
後台:
protected void button1_click(object sender, eventargs e)
{
upimagefile(fileupload1);
}
protected void upimagefile(fileupload fileload)
{
if (fileload.hasfile)
{
string filetype = fileload.postedfile.contenttype;
if (filetype == "image/bmp" || filetype == "image/pjpeg" || filetype == "image/gif" || filetype == "image/png")
{
string loadpath = fileload.postedfile.filename; //等待上傳檔案的本地路徑
system.drawing.image img = system.drawing.image.fromfile(loadpath);
if (img.height > 100 || img.width > 100)
{
fileinfo info = new fileinfo(loadpath);
string fname = info.name; //擷取原檔案名稱
string filename = datetime.now.tostring("yymmddhhmmss") + fname; //在檔案名稱中加入時間
string imgpath = server.mappath("/upfile/orimages/") + filename; //原檔案路徑
string thpath = server.mappath("/upfile/thimages/") + filename; //縮圖路徑
fileload.saveas(imgpath); //儲存原圖片
makethumnail(imgpath, thpath); //產生縮圖
}
else
{
//圖片尺寸太小
}
}
else
{
//檔案格式不對
}
}
}
protected void makethumnail(string orpath, string thpath)
{
system.drawing.image img = system.drawing.image.fromfile(orpath);
int width = 100; //設定縮圖的寬為100
int height = img.height * width / img.width; //縮圖的高按比例縮小
system.drawing.image bitmap = new system.drawing.bitmap(width, height); //建立一個空位元影像
system.drawing.graphics g = system.drawing.graphics.fromimage(bitmap); //建立畫板
g.interpolationmode = system.drawing.drawing2d.interpolationmode.high; //設定為高品質插值
g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality; //指定高品質低速度呈現
g.clear(color.transparent);
g.drawimage(img, new rectangle(0, 0, width, height));
try
{
bitmap.save(thpath, system.drawing.imaging.imageformat.jpeg); //以jpg格式儲存圖片
}
catch (system.exception e)
{
throw e;
}
finally
{
img.dispose();
bitmap.dispose();
g.dispose();
}
}