Avatar of legionl2k
legionl2k asked on

Fileupload to SQL DB and FIledownload using visual studio 2008

HI Experts,
I am trying to creat a fileupload page in my ASP.NET web project. I need to upload files to a SQL database. The files will be larger than the 8000byte limit of the varbinary data type. I cannot use varbinary(max) my server does not have this in the web controls database setup.( What is the best way to store files of say 1 - 5mb in size ) do i need  to upload files to a directory on the server and store the file information and Path in the DB. I need to creat a file download link on the datagrid that enables users to download the files off the server too . I have tried several of the tutorials on the net but to no end. Every where I read how simple this is with the new ASP.NET. I beg to differ, I have been on this for days.
.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
legionl2k

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
graye

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Dustin Hopkins

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Dustin Hopkins

Opps sorry graye I didn't see your post.
ASKER
legionl2k

Hey Thanks, people.

I changed the datatype to "image" and now I can upload larger files Yipeee!
Now to the next problem, I am uploading .PDF's and .ZIP's. So far I have manged to work out how to creat a download link column on my datagrid. But when I click it for my .ZIP files to download it gets the name of the file right but says its a web form ( not a zip). If I try my .PDF file it works fine and downloads. I suppose what I am asking is how to make sure when the user clicks the file to download the application recognises it as a zip or pdf and the system recognises it when downloading. I have attached my code for my fileupload (code behind page) and my getfile(code behind page).

Thanks.
FILEUPLOAD CODE BEHIND PAGE....
 
Imports System.Data.SqlClient
Imports System.Data
 
Partial Class _Default
    Inherits System.Web.UI.Page
    
    Protected Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Upload.Click
		     
	        
           
            Dim fileUpload1 As FileUpload = CType(Me.FindControl("fileUpload1"), FileUpload)
			Dim iLength As Integer  = CType(FileUpload1.PostedFile.InputStream.Length, Integer)
                   If iLength = 0 Then Exit Sub 'not a valid file 
			Dim bytContent As Byte()
			ReDim bytContent(iLength) 'byte array, set to file size 	   
        'Make sure a file has been successfully uploaded
        If fileUpload1.PostedFile Is Nothing OrElse String.IsNullOrEmpty(fileUpload1.PostedFile.FileName) OrElse fileUpload1.PostedFile.InputStream Is Nothing Then
            Label1.Text = "Please Upload Valid ZIP/PDF file"
            Exit Sub
        End If
        'Make sure we are dealing with a JPG or GIF file
        Dim extension As String = System.IO.Path.GetExtension(fileUpload1.PostedFile.FileName).ToLower()
        Dim MIMEType As String = Nothing
        Select Case extension
            Case ".pdf"
                MIMEType = "pdf"
            Case ".zip", ".rar"
                MIMEType = ".zip"
	   Case ".xls"
	       MIMEType = "xls"
            
            Case Else
                'Invalid file type uploaded
                Label1.Text = "Not a Valid file format"
                Exit Sub
        End Select
      'Connect to the database and insert a new record into Attachments
        Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDbConn").ConnectionString)
            Const SQL As String = "INSERT INTO [tblAttachments] ([FileName], [FileSize], [FileData],[ContentType]) VALUES (@FileName, @FileSize, @FileData,@ContentType)"
            Dim myCommand As New SqlCommand(SQL, myConnection)
            myCommand.Parameters.AddWithValue("@FileName", TextBox1.Text.Trim())
            myCommand.Parameters.AddWithValue("@ContentType", MIMEType)
            myCommand.Parameters.AddWithValue("@DateAdded", Now())
			myCommand.Parameters.AddWithValue("@FileSize", iLength)
            'Load FileUpload's InputStream into Byte array
            Dim fileBytes(fileUpload1.PostedFile.InputStream.Length) As Byte
            fileUpload1.PostedFile.InputStream.Read(fileBytes, 0, fileBytes.Length)
            myCommand.Parameters.AddWithValue("@FileData", fileBytes)
            myConnection.Open()
            myCommand.ExecuteNonQuery()
            myConnection.Close()
        End Using
    End Sub
End Class
 
 
GETFILE CODE BEHIND PAGE....
 
Imports System.Data.SqlClient
 
Partial Class getfile
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Attachment_ID As Integer = Convert.ToInt32(Request.QueryString("Attachment_ID"))
 
        'Connect to the database and bring back the image contents & MIME type for the specified picture
        Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDbConn").ConnectionString)
 
            Const SQL As String = "SELECT [ContentType], [FileName], [FileData], [FileSize] FROM [tblAttachments] WHERE [Attachment_ID] = @Attachment_ID"
            Dim myCommand As New SqlCommand(SQL, myConnection)
            myCommand.Parameters.AddWithValue("@Attachment_ID", Attachment_ID)
 
            myConnection.Open()
            Dim myReader As SqlDataReader = myCommand.ExecuteReader
 
            If myReader.Read Then
             	Response.ContentType = myReader("ContentType").ToString
            	Response.OutputStream.Write(CType(myReader("FileData"), Byte()), 0, CInt(myReader("FileSize")))
            	Response.AddHeader("Content-Disposition", "attachment;filename=" + myReader("FileName").ToString()) 
			Else
            Response.Write("File Not Found.")
            End If
			
 
            myReader.Close()
            myConnection.Close()
        End Using
 
    End Sub
End Class

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes