2012-07-11 154 views
1

我在做一個用戶配置文件,用戶首先選擇的圖片,並上傳到這個代碼的文件夾,之後顯示的圖像上傳:圖像路徑到SQL數據庫

protected void btnUpload_Click(object sender, EventArgs e) 
{ 
    // Initialize variables 
    string sSavePath; 
    string sThumbExtension; 
    int intThumbWidth; 
    int intThumbHeight; 

    // Set constant values 
    sSavePath = "images/"; 
    sThumbExtension = "_thumb"; 
    intThumbWidth = 160; 
    intThumbHeight = 120; 

    // If file field isn’t empty 
    if (filUpload.PostedFile != null) 
    { 
     // Check file size (mustn’t be 0) 
     HttpPostedFile myFile = filUpload.PostedFile; 
     int nFileLen = myFile.ContentLength; 
     if (nFileLen == 0) 
     { 
      lblOutput.Text = "El archivo no fue cargado."; 
      return; 
     } 

     // Check file extension (must be JPG) 
     if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg") 
     { 
      lblOutput.Text = "El archivo debe tener una extensión JPG"; 
      return; 
     } 

     // Read file into a data stream 
     byte[] myData = new Byte[nFileLen]; 
     myFile.InputStream.Read(myData, 0, nFileLen); 

     // Make sure a duplicate file doesn’t exist. If it does, keep on appending an 
     // incremental numeric until it is unique 
     string sFilename = System.IO.Path.GetFileName(myFile.FileName); 
     int file_append = 0; 
     while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename))) 
     { 
      file_append++; 
      sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) 
          + file_append.ToString() + ".jpg"; 
     } 

     // Save the stream to disk 
     System.IO.FileStream newFile 
       = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), 
              System.IO.FileMode.Create); 
     newFile.Write(myData, 0, myData.Length); 
     newFile.Close(); 

     // Check whether the file is really a JPEG by opening it 
     System.Drawing.Image.GetThumbnailImageAbort myCallBack = 
         new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 
     Bitmap myBitmap; 
     try 
     { 
      myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename)); 

      // If jpg file is a jpeg, create a thumbnail filename that is unique. 
      file_append = 0; 
      string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) 
                + sThumbExtension + ".jpg"; 
      while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile))) 
      { 
       file_append++; 
       sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + 
           file_append.ToString() + sThumbExtension + ".jpg"; 
      } 

      // Save thumbnail and output it onto the webpage 
      System.Drawing.Image myThumbnail 
        = myBitmap.GetThumbnailImage(intThumbWidth, 
               intThumbHeight, myCallBack, IntPtr.Zero); 
      myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile)); 
      imgPicture.ImageUrl = sSavePath + sThumbFile; 


      // Displaying success information 
      lblOutput.Text = "El archivo fue cargado con exito!"; 

      // Destroy objects 
      myThumbnail.Dispose(); 
      myBitmap.Dispose(); 
     } 
     catch (ArgumentException errArgument) 
     { 
      // The file wasn't a valid jpg file 
      lblOutput.Text = "No es un archivo .jpg valido"; 
      System.IO.File.Delete(Server.MapPath(sSavePath + sFilename)); 
     } 
    } 
} 

在此之後,用戶與個人資料(姓名,電子郵件等)的其他領域完成,有一個保存按鈕,並用此保存到數據庫:

這就是前面代碼

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pruebaConnectionString %>" 
    InsertCommand="INSERT INTO Curriculum(Nombre, Correo) VALUES (@TextBox1, @TextBox2)"> 
    <InsertParameters> 
     <asp:ControlParameter ControlID="TextBox1" DefaultValue="" Name="TextBox1" PropertyName="Text" /> 
     <asp:ControlParameter ControlID="TextBox2" DefaultValue="" Name="TextBox2" PropertyName="Text" />      
    </InsertParameters> 
</asp:SqlDataSource> 

其實有鐵道部Ë領域,而是使之短,我只是複製第2,農佈雷場是唯一不能爲空數據庫

代碼背後:

protected void Button1_Click(object sender, EventArgs e) 
{ 
       SqlDataSource1.Insert(); 

     String strConn = "Data Source=TOSHI;Initial Catalog=prueba;Integrated Security=True"; 
     SqlConnection conn = new SqlConnection(strConn); 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = conn; 
     string strQuery = "Insert into curriculum (imagen) values (@imgPicture)"; 
     cmd.CommandText = strQuery; 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.AddWithValue("@imgPicture", (imgPicture.ImageUrl == null ? (object)DBNull.Value : (object)imgPicture.ImageUrl)); 
     conn.Open(); 
     cmd.ExecuteNonQuery(); 
     conn.Close(); 
} 

現在我想要做的是當用戶點擊保存按鈕(或方法button1_click上的內容)時,圖像url將保存到字段Imagen的數據庫中,該字段是一個varchar 50,但不起作用,我得到:無法插入值NULL納入'Nombre'列,'prueba.dbo.Curriculum'表;列不允許有空值。 INSERT失敗。 該聲明已被終止。

但是,如果我離開button1_click方法只有SqlDataSource1.Insert();這些字段被保存到數據庫中。

任何想法如何將圖像url保存到數據庫?希望我對我的解釋清楚!

謝謝! :D

回答

0

您是否正在嘗試創建新記錄(在哪個Canse中您需要指定所有值)還是您正在更新記錄?

目前,您的代碼正在嘗試執行INSERT,它將在課程表中創建一條新記錄,但您只設置1值。也許你想要做一個更新呢?

string strQuery = "UPDATE curriculum SET imagen = @imgPicture WHERE Nombre = ???"; 
+0

你是完全正確的!它的更新!但是在哪裏呢? – Ivelisse 2012-07-11 03:47:14

+0

現在正在工作,我寫了這個字符串strQuery =「更新課程設置imagen = @imgPicture」;但更新所有記錄不僅是我插入的那個 – Ivelisse 2012-07-11 03:58:40

+0

您需要更換???用剛剛插入的nombre的值,也許是TextBox1.Text? – Greg 2012-07-12 00:03:40