Welcome Guest! You need to login or register to make posts.

Notification

Icon
Error

Options
Go to last post Go to first unread
asphaltninja  
#1 Posted : Wednesday, February 10, 2010 2:55:58 AM(UTC)
asphaltninja

Rank: Newbie

Groups: Member
Joined: 2/10/2010(UTC)
Posts: 3

The insert sql statement I have no problem with, but I'm unclear on the proper VB.NET code for uploading to the database. I want to store image name, image contenttpe and image data in a sql table, and then retrieve them later on to display. Also I'd like the ocde to be able to process multiple images should the user upload mor than one image at a time. Thanks in advance for any help you can provide.
Fedor  
#2 Posted : Wednesday, February 10, 2010 3:48:30 AM(UTC)
Fedor

Rank: Advanced Member

Groups: Member, Administration, Moderator
Joined: 7/28/2003(UTC)
Posts: 1,558

Thanks: 5 times
Was thanked: 62 time(s) in 61 post(s)
Please read:

ASP.NET code sample to upload to SQL database?

The sample is in C#, but I have converted it to VB.NET using Developer Fusion C# to VB converter. Please note, the code is untested.

Uploading:

Code:
<%@ Page Language="VB" AutoEventWireup="true" ValidateRequest="false" Debug="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Globalization" %>

<script runat="server">Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim connection As New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("ImageUploaderConnectionString").ConnectionString)
    
    Dim command As New SqlCommand("INSERT INTO [ImageUploader].[dbo].[File]([FileName], " & "[ContentType], [Size], [LastModified], [FileData] ,[ThumbnailData]) " & "VALUES (@FileName,@ContentType,@Size, @LastModified, @FileData, " & "@ThumbnailData)", connection)
    
    Dim fileName As New SqlParameter("@FileName", SqlDbType.NVarChar, 100)
    command.Parameters.Add(fileName)
    
    Dim contentType As New SqlParameter("@ContentType", SqlDbType.NVarChar, 100)
    command.Parameters.Add(contentType)
    
    Dim size As New SqlParameter("@Size", SqlDbType.Int)
    command.Parameters.Add(size)
    
    Dim lastModified As New SqlParameter("@LastModified", SqlDbType.DateTime)
    command.Parameters.Add(lastModified)
    
    Dim fileData As New SqlParameter("@FileData", SqlDbType.Image)
    command.Parameters.Add(fileData)
    
    Dim thumbnailData As New SqlParameter("@ThumbnailData", SqlDbType.Image)
    command.Parameters.Add(thumbnailData)
    
    connection.Open()
    
    Try
        Dim fileCount As Integer = Int32.Parse(Request.Form("FileCount"))
        
        For i As Integer = 1 To fileCount
            'Get source file and thumbnails and save it to DB.
            Dim sourceFile As HttpPostedFile = Request.Files("SourceFile_" & i)
            Dim thumbnail1File As HttpPostedFile = Request.Files("Thumbnail1_" & i)
            
            fileName.Value = Path.GetFileName(sourceFile.FileName)
            
            'Content-type contains:
            'image/jpeg; charset=utf-8; Content-Transfer-Encoding: binary
            Dim ct As String = sourceFile.ContentType
            Dim ind As Integer = ct.IndexOf(";")
            If ind > 0 Then
                ct = ct.Substring(0, ind)
            End If
            contentType.Value = ct
            
            size.Value = sourceFile.ContentLength
            
            'Last modification date of the original Nth file in EXIF-style format:
            'YYYY:MM:DD hh:mm:ss 
            Dim info As New DateTimeFormatInfo()
            info.ShortDatePattern = "yyyy:MM:dd HH:mm:ss"
            lastModified.Value = DateTime.ParseExact(Request.Form("SourceFileLastModifiedDateTime_" & i), "d", info)
            
            Dim fd As Byte() = New Byte(sourceFile.ContentLength - 1) {}
            sourceFile.InputStream.Read(fd, 0, sourceFile.ContentLength)
            fileData.Value = fd
            
            Dim td As Byte() = New Byte(thumbnail1File.ContentLength - 1) {}
            thumbnail1File.InputStream.Read(td, 0, thumbnail1File.ContentLength)
            thumbnailData.Value = td
            
            command.ExecuteNonQuery()
        Next
    Finally
        connection.Close()
    End Try
End Sub
</script>


Displaying:

Code:
<%@ Page Language="VB" AutoEventWireup="true" ValidateRequest="false" Debug="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Globalization" %>

<script runat="server">Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim sql As String
    
    If Not [String].IsNullOrEmpty(Request.QueryString("t")) Then
        sql = "SELECT ThumbnailData As [Data], FileName, ContentType FROM [File] WHERE ID = @ID"
    Else
        sql = "SELECT FileData As [Data], FileName, ContentType FROM [File] WHERE ID = @ID"
    End If
    
    Dim connection As New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("ImageUploaderConnectionString").ConnectionString)
    
    Dim command As New SqlCommand(sql, connection)
    command.Parameters.AddWithValue("@ID", Int32.Parse(Request.QueryString("id")))
    
    connection.Open()
    
    Try
        Dim reader As SqlDataReader = command.ExecuteReader()
        
        If reader.Read() Then
            Response.ContentType = reader("ContentType").ToString()
            Response.AppendHeader("Content-Disposition", [String].Format("attachment; filename={0}", HttpUtility.UrlEncode(reader("FileName").ToString()).Replace("+", "%20")))
            Dim data As Byte() = DirectCast(reader("Data"), Byte())
            Response.OutputStream.Write(data, 0, data.Length)
        End If
        
        reader.Close()
    Finally
        connection.Close()
    End Try
End Sub
</script>

Edited by user Wednesday, February 10, 2010 3:49:09 AM(UTC)  | Reason: Not specified

Best regards,
Fedor Skvortsov
asphaltninja  
#3 Posted : Wednesday, February 10, 2010 10:32:42 AM(UTC)
asphaltninja

Rank: Newbie

Groups: Member
Joined: 2/10/2010(UTC)
Posts: 3

edit: I am now receiving this error when I try to access the page I placed the imageuploader onto.

Code:
[SecurityException: Request for the permission of type 'System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +54
   System.Configuration.BaseConfigurationRecord.CheckPermissionAllowed(String configKey, Boolean requirePermission, Boolean isTrustedWithoutAptca) +108



Edited by user Wednesday, February 10, 2010 11:43:53 PM(UTC)  | Reason: Not specified

asphaltninja  
#4 Posted : Wednesday, February 10, 2010 4:49:39 PM(UTC)
asphaltninja

Rank: Newbie

Groups: Member
Joined: 2/10/2010(UTC)
Posts: 3

Figured it out. Had to add

Code:
<trust level="Full" />


To the web.config file. Not sure if this is the best fix but it works! I'll try the code tomorrow and report back.

Edited by user Wednesday, February 10, 2010 11:44:20 PM(UTC)  | Reason: Not specified

Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.