Store uploaded files on web server or in SQL?

Curious as to which way you think is the best.  From ease of coding, it's simplier to file on the server it seems than to store in sql.  So, if you prefer sql, do you have a sample you can send me? 


Never make important decisions on a Monday!
0
funluckykitty
4/29/2008 8:30:16 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

3 Replies
896 Views

Similar Articles

[PageSpeed] 50
Get it on Google Play
Get it on Apple App Store

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=414

Actually, I prefer the filesystem. 

 


Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
4/29/2008 9:07:30 PM

Hi,

Look at the following code which i have to stored images in windows application(not web) in the sql server but this is not the best practice to store images.

If you are using documents and so on files i prefer you to store on web server, this will boost performance.

 

Code to store and retrieve images to and from sql server

-------------------------------------------------------------------------------------------

 

 Private Sub storeimage()
        'Procedure to store image
        Try
            Dim cn As New SqlConnection
            'Dim str As String = "Data Source=.\SQLExpress;Initial Catalog=BLMSDB;Integrated Security=True;Pooling=False"

            Dim str As String = BLMSFAR.My.Settings.BLMSFARDatabaseConnectionString
            cn.ConnectionString = str
          
            Dim cmd As New SqlCommand("InsertImages", cn)
            cmd.CommandType = CommandType.StoredProcedure

            Dim strImageFilePath As String = OpenFileDialog1.FileName

            Dim Filename As String = Path.GetFileName(OpenFileDialog1.FileName)

            Dim fsImageFile As New FileStream(strImageFilePath, _
            FileMode.Open, FileAccess.Read)
            Dim bytImageData(fsImageFile.Length() - 1) As Byte
            fsImageFile.Read(bytImageData, 0, bytImageData.Length)
            fsImageFile.Close()


            'Dim LNO As New SqlParameter("@LNO", SqlDbType.Int, t, ParameterDirection.Input)
            'cmd.Parameters.AddWithValue("@LNO", StoreLNO)
            'Dim LNO As New SqlParameter("@LNO", SqlDbType.Int)
            'cmd.Parameters("@LNO").Value = StoreLNO


            Dim Title As New SqlParameter("@Title", SqlDbType.VarChar, _
                                   250, ParameterDirection.Input, False, _
                                  0, 0, Nothing, DataRowVersion.Current, Filename)

            Dim Picture As New SqlParameter("@Picture", SqlDbType.Image, _
                                bytImageData.Length, ParameterDirection.Input, False, _
                                0, 0, Nothing, DataRowVersion.Current, bytImageData)

            cmd.Parameters.AddWithValue("@LNO", StoreLNO)
            cmd.Parameters.Add(Title)
            cmd.Parameters.Add(Picture)

            cn.Open()
            cmd.ExecuteNonQuery()
            cn.Close()
            Me.TextBox1.Text = Nothing

        Catch ex As Exception
            MessageBox.Show(ex.Message)

        End Try
    End Sub

---------------------------------------------------------------------------

Private Sub DownloadImages(ByVal DirectoryFullPath As String)

Try

Dim cn As New SqlConnection

'Dim str As String = "Data Source=.\SQLExpress;Initial Catalog=BLMSDB;Integrated Security=True;Pooling=False"

Dim str As String = BLMSFAR.My.Settings.BLMSFARDatabaseConnectionString

cn.ConnectionString = str

Dim cmd As New SqlCommand("DownloadImages", cn)

cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.AddWithValue(
"@License_No", StoreLNO)

cn.Open()

Dim docfilereader As SqlDataReader

docfilereader = cmd.ExecuteReader

While docfilereader.Read()

Dim filedata(docfilereader.GetBytes(2, 0, Nothing, 0, Integer.MaxValue) - 1) As Byte

docfilereader.GetBytes(2, 0, filedata, 0, filedata.Length)

Dim Title As String = docfilereader(1)

Dim s As String

s = DirectoryFullPath & "\" & Title

My.Computer.FileSystem.WriteAllBytes(s, filedata, True)

End While

cn.Close()

Process.Start(DirectoryFullPath)

Catch ex As Exception

MsgBox(ex.Message.ToString)

End Try

End Sub

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Look at the following example for storing files on Web Server

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Import Namespace="System.IO" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server" >

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

Dim filepath As String = MapPath("~/UploadImages/")

Dim dir As New DirectoryInfo(filepath)

DataList1.DataSource = dir.GetFiles()

DataList1.DataBind()

End Sub

Protected Sub ars(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

If (FileUpload1.HasFile) Then

If (CheckFileType(FileUpload1.FileName)) Then

Dim filepath As String = "~/UploadImages/" & FileUpload1.FileName

FileUpload1.SaveAs(MapPath(filepath))

End If

End If

End Sub

Function CheckFileType(ByVal fName As String) As Boolean

Dim ext As String = Path.GetExtension(fName)

Select Case ext.ToLower()

Case ".jpg"

Return True

Case ".jpeg"

Return True

Case ".bmp"

Return True

Case ".png"

Return True

Case ".tif"

Return True

Case ".gif"

Return True

Case Else

Return False

End Select

End Function</script>

 

 

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

</div>

<asp:Label ID="Label1" runat="server" Text="FileName"></asp:Label>

<asp:FileUpload ID="FileUpload1" runat="server" />

<br />

<asp:Button ID="Button1" runat="server" Text="Upload Image" OnClick="ars" />

<br />

<br />

<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" Style="text-align: center;">

<ItemTemplate>

<asp:Image ID="Image1" runat="server" Style="width: 200px" ImageUrl='<%# Eval("Name","~/UploadImages/{0}") %>' />

<%# Eval("Name")%>

</ItemTemplate>

</asp:DataList>

</form>

</body>

</html>

 

Thanks

Best Regards

Arshad 

 


Please Mark as Answer if the post is helpful to you.
0
arshadtop
4/30/2008 5:45:20 AM

Look at the following link , this may helpful for you.

http://chiragrdarji.wordpress.com/2007/08/31/storing-and-retrieving-docpdfxls-files-in-sql-server/

 

Thanks.

Regards

Arshad


Please Mark as Answer if the post is helpful to you.
0
arshadtop
4/30/2008 5:45:22 AM
Reply:

Similar Artilces:

how to save file (stored on SQL server) to file/web server?
Hi Experts, I got files stored on SQL server db. I would like to be able to save them onto file/web server. I know how to retrieve them, but not sure how to save to file/web server. Please help. Thanks so much. Below are codes for retrieving file info from sql server:Dim strFileName As String = Quote.GetQuoteFileByQuoteFileID(CInt(selectedQuoteFileID)).Tables(0).Rows(0).Item("QuoteFileName")Dim strFileType As String = Quote.GetQuoteFileByQuoteFileID(CInt(selectedQuoteFileID)).Tables(0).Rows(0).Item("QuoteFileType")Dim strFileSize As Integer = Quote.GetQuoteFileByQuoteFileID(CInt(selectedQ...

How to upload files (stored on SQL) to web server?
Hi Experts, I got files stored on SQL server db. I would like to be able to upload them onto web server. I know how to retrieve th! em, but not sure how to upload them to web server. Please help. Thanks so much. Below are codes for retrieving file info from sql server: Dim strFileName As String = Quote.GetQuoteFileByQuoteFileID(CInt(selectedQuoteFileID)).Tables(0).Rows(0).Item("QuoteFileName")Dim strFileType As String = Quote.GetQuoteFileByQuoteFileID(CInt(selectedQuoteFileID)).Tables(0).Rows(0).Item("QuoteFileType")Dim strFileSize As Integer = Quote.GetQuoteFileByQuoteFileID(CInt(s...

How to upload or copy file from web server to remote sql server
  Hi All,   q. How to upload or copy file from web server to remote server..?.  I want to uploaded excel file from client machine to remote sql server via web server.   i did 1st part and i dont know how to send file from wbe server to remote database server  pls give me solution or usefull links iif any one knows how to do this ..   Thanks in advance.     Are you saying you want to send the file there, or extract the spreadsheet data and put it into a database table?    If the former, I suggest setti...

Uploading files to a different file server but not web server
Hi, I want to upload files to a different file server than the web server using asp.net, is that possible?I can use Server.MapPath to store it on the same server. How do I save it to a different machine? What all I need? Do I need IP address? Do I need to have a shared folder on that machine? thank u for the help!!! There is only a few built in ways to get a file from one machine to another in windows.  Things like FTP, HTTP, or File Sharing - you are going to need a path to the server.  You cannot upload directly to that server.  You'll need to upload to your web s...

File Upload to server and save path to uploaded file into a sql database
   I am trying to upload a file to a server and save the path of the uploaded file to a sql 2005 server. I have some code below but im getting the error Object reference not set to an instance of an object. Any help would be greatful. By the way I got this code from these forums and just tweaked them for my website. 1 Dim Fileupload1 As FileUpload = CType(FindControl("FileUpload1"), FileUpload) 2 Dim filePath1 As Label = CType(FindControl("filePath1"), Label) 3 4 If Fileupload1.HasFile Then 5 Try 6 Fileupload1...

Get SourceSafe files and upload to the web server
How can I know where VSS is storing the checked in versions of a web site to upload them to the web server? Thanks.Juliano NunesMCAD | MCP | Microsoft Student Partnerhttp://julianonetfox2.spaces.live.com...

Get URL for a file uploaded to the web-server
Hi I'm wondering if there's an easy way to get the URL for a file uploaded with FileUpload control? I can get the physical path from the webserver by using Server.MapPathThe problem is that this is the local path for the file i get then. Is there a similar way to get the URL instead of the local path from the server? I have a solution, but i don't think it's smart. The way I'm doing it now is by splitting the path into pieces (seperator = \) and write: 'http://servername:port/ + @"/" + strPiece1 + @"/" + strPiece2' and so on. Thanks, Thoma...

Store and get flash files from SQL Server
Hi Everyone, I want to store and get flash files(.swf extension) from sql server. I tried using the image datatype in sql server which stores binary data. Is this correct? Also, how can i get the file out from sql server? Thanks alot, HenryToronto Trade show displays | Toronto Printing Solutions | Toronto Printing Yes. Check out this article on retrieving images from SQL Server (just replace image-specific stuff, which is NOT very much, with flash-specific stuff). http://www.dotnetbips.com/displayarticle.aspx?id=60Darrell Norton, MVPDarrell Norton's BlogPlease mark this ...

I created a website on my localhost with three .mdf files using SQL express but now I get an error when I try to host it on my web server without SQL express. need some help on how to change my connec
An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: An error has occurred whil...

How do setup a directory on a web server to store upload files
I'm trying to store upload images on my webserver but don't know how to create the directory to save the file. Would someone kind enough to show me an example on  how to create the folder Thanks star36 Below is a sample code string storePath = Server.MapPath("~") + "UploadFiles"; if(!System.IO.Directory.Exists(storePath))System.IO.Directory.CreateDirectory(storePath); HCHaissam Abdul MalakMCAD.NET| Blog | ok i saw your link and i tryed to use the method but i got an error on Path.GetFileName. thanks The Path class in under the System.IO namespace. ...

How to get Excel or PDF file stored into SQL server ?
I've created a table in SQL server to store/retrieve binary file, I used image as field type to store that binary and add another filed to store the image type, I saved image file, excel, pdf, word, etc. successfully in an ASP.NET environment, and I can retrieved the image files by add simply two lines as below: Response.ContentType = myDataReader.Item("myImgTyp")Response.BinaryWrite(myDataReader.Item("myImgField")) How, I cannot apply the same way to retrieve file of other type, also whenever I retrieved and save, I cannot handle the file extension as the same file type! If anyone ...

File upload to a server other than the web server.
I have a very simple asp.net upload page. Everything works great when saving the file locally (web server). Things are getting ugly when trying to save files to a different machine (file server, database server,...) So, when using .SaveAs and passing in the UNC path to the new server location I get an *Access denied* error messgae. When mapping a network drive and using the drive letter in the .SaveAs path I get an message saying parts of the path cannot be found. any ideas? thanks  --tolgaApplication Developer Make sure that the account running asp.net web applicaiton(defa...

Urgent! Upload text file to SQL Server in VB.NET
Hi Experts, I am working on an HR Web application which should upload applicant's resume to our SQL Server 2000, a BLOB column.However, it inserts without error, but the resume isn't stored in table at all. The table structure is:CREATE TABLE [dbo].[Mgmt_App_Resume_Table] ( [Applicant_ID] [smallint] NULL , [App_Resume] [image] NULL  ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]After the program executed, the Applicant_ID is inserted fine, but the App_Resume column is empty.  The file I uploaded is a MS word doc. and it's a resume.....Where did I do wrong?  Ple...

Getting data form SQL Server 2005 to a Web.SiteMap file
I want read a hierarchal data table in SQL Server 2005 to write My Web.SiteMap file. How I to do it? web.sitemap is a static file used by the XmlSiteMapProvider if you know your site navigation at development time. If you have a data-driven navigation, then you should consider creating your own SiteMapProvider. -Brock  DevelopMentorhttp://staff.develop.com/ballen...

Web resources about - Store uploaded files on web server or in SQL? - asp.net.getting-started

Help:Files - Wikipedia, the free encyclopedia
... the first step in using an image or other media file is to upload it to Wikimedia Commons , but for legal reasons, some files must be uploaded ...

Instagram Deleting Photos Uploaded Via Third-Party Windows Phone 8 App Instance
... has apparently run afoul of Facebook-owned photo-sharing network Instagram ’s policies, as Developer Daniel Gary told The Verge photos uploaded ...

YouTube Integrates Facebook Connect to Autoshare Uploaded Videos
... rivals on multiple fronts, YouTube announced today that it has just launched Facebook Connect integration, making it easy to autoshare uploaded ...

How many photos are uploaded to Facebook each day?
Answer (1 of 2): We currently have over 200 million photos uploaded per day, or around 6 billion per month. There are currently almost 90 billion ...

Gridplay - The Vine & IG Music Video Maker, Uploaded from Your Camera Roll on the App Store on iTunes ...
Get Gridplay - The Vine & IG Music Video Maker, Uploaded from Your Camera Roll on the App Store. See screenshots and ratings, and read customer ...


Happy Iranians - Original uploaded Iran version of Pharrell Williams " Happy " video - YouTube
Join me at https://www.facebook.com/Sufinumeerpage Young Iranians Arrested For Dancing In 'Happy' Pharrell Video Age: 25, Crime: Happiness About ...

#MyDubai: half a million images uploaded in four months
The number of hits over such a short period of time show how the project has sparked UAE residents’ imaginations, the state news agency Wam reported. ...

Throwback of the Day: Watch the First Video Ever Uploaded to YouTube
This 18-second clip titled “Me at the Zoo” is the very first video ever uploaded to the site 10 years ago today (April 23, 2005). And while it ...

A million minutes of history uploaded online
The AP and British Movietone will upload more than a million minutes of historical footage to YouTube.

Resources last updated: 12/28/2015 6:53:59 PM