2009-04-18 3 views
0

업로드 및 이미지 크기 조정에 성공했습니다. 이제 이미지 이름을 데이터베이스에 삽입하고 싶습니다.데이터베이스에 이미지 이름을 삽입하는 방법은 무엇입니까?

SQL Server를 사용하고 있습니다. 이 테이블의 이름은 images이며 두 개의 열, imageidimagenamestring(invarchar(max))입니다. imagename 열에 저장된 파일 이름이 필요하며 imageid은 신원이어야합니다.

는 여기에 지금까지 가지고있는 코드입니다 :

Imports System.Drawing 
Imports System.Drawing.Drawing2D 
Imports System.Drawing.Imaging 
Imports System.IO 
Imports System.Data.SqlClient 
Imports System.Data 
Partial Class _Default 
    Inherits System.Web.UI.Page 

    Protected Sub btnupload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnupload.Click 
     Response.Write("Done") 
     If (IsPostBack) Then 
      HandleUploadedFile() 
     End If 
    End Sub 
    Private Sub HandleUploadedFile() 
     ' get the root of the web site 
     Dim root As String = Server.MapPath("~/") 

     ' clean up the path 
     If Not root.EndsWith("\") Then 
      root += "\" 
     End If 

     ' make a folder to store the images in 
     Dim fileDirectory As String = root & "Images/" 

     ' create the folder if it does not exist 
     If Not System.IO.Directory.Exists(fileDirectory) Then 
      System.IO.Directory.CreateDirectory(fileDirectory) 
     End If 

     ' make a link to the new file 
     Dim link As String = "<a href='Images/{0}' target='_blank'>{1}</a>{2}{3}" 

     ' loop through the file in the request 
     For i As Integer = 0 To Request.Files.Count - 1 

      ' get the file instance 
      Dim fi As HttpPostedFile = Request.Files.[Get](i) 

      ' create a byte array to store the file bytes 
      Dim fileBytes As Byte() = New Byte(fi.ContentLength - 1) {} 

      ' fill the byte array 
      Using stream As System.IO.Stream = fi.InputStream 
       stream.Read(fileBytes, 0, fi.ContentLength) 
      End Using 

      ' create a random file name 
      Dim fileName As String = Guid.NewGuid().ToString() 

      ' write the original file to the file system 
      File.WriteAllBytes(fileDirectory + fileName & ".jpg", fileBytes) 
      litText.Text += String.Format(link, fileName & ".jpg", fileName & " Original", "<br/>", "") 

      ' write the resized file to the file system 
      File.WriteAllBytes(fileDirectory + fileName & "_small.jpg", ResizeImageFile(fileBytes, 100)) 
      litText.Text += String.Format(link, fileName & "_small.jpg", fileName & " Small", "<br/>", "<br/>") 

      ' cleanup 
      litText.Visible = True 
      fileBytes = Nothing 
     Next 
    End Sub 
    Private Shared Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte() 
     Using oldImage As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile)) 
      Dim newSize As Size = CalculateDimensions(oldImage.Size, targetSize) 
      Using newImage As New Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb) 
       Using canvas As Graphics = Graphics.FromImage(newImage) 
        canvas.SmoothingMode = SmoothingMode.AntiAlias 
        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic 
        canvas.PixelOffsetMode = PixelOffsetMode.HighQuality 
        canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize)) 
        Dim m As New MemoryStream() 
        newImage.Save(m, ImageFormat.Jpeg) 
        Return m.GetBuffer() 
       End Using 
      End Using 
     End Using 
    End Function 
    Private Shared Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size 
     Dim newSize As New Size() 
     If oldSize.Height > oldSize.Width Then 
      newSize.Width = CInt((oldSize.Width * (CSng(targetSize)/CSng(oldSize.Height)))) 
      newSize.Height = targetSize 
     Else 
      newSize.Width = targetSize 
      newSize.Height = CInt((oldSize.Height * (CSng(targetSize)/CSng(oldSize.Width)))) 
     End If 
     Return newSize 
    End Function 
End Class 
+0

그 코드 일 수도 있지만 무엇이 문제입니까? –

+0

데이터베이스에 이미지 이름을 추가하는 방법을 알고 싶습니다. –

+0

어떤 종류의 데이터베이스입니까? 어떤 서버? 어떤 테이블 스키마입니까? 어떤 OS인가? 어떤 실행 컨텍스트? 어떤 런타임 환경? 그냥 "내가 이전에 설명하지 않은 것을 수행하는 방법을 알고 싶다"라는 설명은 실제로는 설명이 아닙니다 :) –

답변

1

먼저 당신은 당신의 연결 문자열을 알아야합니다. 코드에서 SQLClient를 참조하기 때문에 SQL Server를 사용하고 있다고 가정하므로 here으로보아야합니다. 다음으로 SQLCommand 개체의 ExecuteNonQuery 메서드를 사용하려고합니다. 아래 샘플을 붙여 넣었습니다. SQLCommand 개체 here에 대한 자세한 내용을 볼 수 있습니다. 그리고이 site은 Insert 문을 다룹니다.

Public Sub SaveNameInDatabase(ByVal fileName As String, ByVal connectionString As String) 
    Using connection As New SqlConnection(connectionString) 
String query = String.format("INSERT INTO Files_Table (FileName) Values (\"{0}\")",fileName) 
     Dim command As New SqlCommand(, connection) 
     command.Connection.Open() 
     command.ExecuteNonQuery() 
    End Using 
End Sub 
관련 문제