回覆列表
  • 1 # 使用者1613658378935

    解決方法一般有兩種:1、將圖片儲存的路徑儲存到資料庫;2、將圖片以二進位制資料流的形式直接寫入資料庫欄位中。以下為具體方法:一、儲存圖片的上傳路徑到資料庫:stringuppath="";//用於儲存圖片上傳路徑//獲取上傳圖片的檔名stringfileFullname=this.FileUpload1.FileName;//獲取圖片上傳的時間,以時間作為圖片的名字可以防止圖片重名stringdataName=DateTime.Now.ToString("yyyyMMddhhmmss");//獲取圖片的檔名(不含副檔名)stringfileName=fileFullname.Substring(fileFullname.LastIndexOf("\\")+1);//獲取圖片副檔名stringtype=fileFullname.Substring(fileFullname.LastIndexOf(".")+1);//判斷是否為要求的格式if(type=="bmp"||type=="jpg"||type=="jpeg"||type=="gif"||type=="JPG"||type=="JPEG"||type=="BMP"||type=="GIF"){//將圖片上傳到指定路徑的資料夾this.FileUpload1.SaveAs(Server.MapPath("~/upload")+"\\"+dataName+"."+type);//將路徑儲存到變數,將該變數的值儲存到資料庫相應欄位即可uppath="~/upload/"+dataName+"."+type;}二、將圖片以二進位制資料流直接儲存到資料庫:引用如下名稱空間:usingSystem.Drawing;usingSystem.IO;usingSystem.Data.SqlClient;設計資料庫時,表中相應的欄位型別為iamge儲存://圖片路徑stringstrPath=this.FileUpload1.PostedFile.FileName.ToString();//讀取圖片FileStreamfs=newSystem.IO.FileStream(strPath,FileMode.Open,FileAccess.Read);BinaryReaderbr=newBinaryReader(fs);byte[]photo=br.ReadBytes((int)fs.Length);br.Close();fs.Close();//存入SqlConnectionmyConn=newSqlConnection("DataSource=.;InitialCatalog=stumanage;UserID=sa;Password=123");stringstrComm="INSERTINTOstuInfo(stuid,stuimage)VALUES(107,@photoBinary)";//操作資料庫語句根據需要修改SqlCommandmyComm=newSqlCommand(strComm,myConn);myComm.Parameters.Add("@photoBinary",SqlDbType.Binary,photo.Length);myComm.Parameters["@photoBinary"].Value=photo;myConn.Open();if(myComm.ExecuteNonQuery()>0){this.Label1.Text="ok";}myConn.Close();讀取:...連線資料庫字串省略mycon.Open();SqlCommandcommand=newSqlCommand("selectstuimagefromstuInfowherestuid=107",mycon);//查詢語句根據需要修改byte[]image=(byte[])command.ExecuteScalar();//指定從資料庫讀取出來的圖片的儲存路徑及名字stringstrPath="~/Upload/zhangsan.JPG";stringstrPhotoPath=Server.MapPath(strPath);//按上面的路徑與名字儲存圖片檔案BinaryWriterbw=newBinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));bw.Write(image);bw.Close();//顯示圖片this.Image1.ImageUrl=strPath;採用這兩種方式可以根據實際需求靈活選擇。

  • 中秋節和大豐收的關聯?
  • 物業管家的十大禁忌?