4Guys Upload File includes PDF/DOC files


I'm using the example File Upload Code seen here:

This code is great however I want to modify it to dynamically allow any file format.

At the moment I have adjusted the code to recognized PDF's and DOC's (see bold text in code). The problem is when I retrieve the files from the Database, the image files exist and show properly, the PDF's work as well, but the DOC files do NOT work.The DOC file download link prompts the user to download the .ASPX file NOT the named DOC file.

 How can I setup the DOC's download link to download properly?



 'Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'If Cancel button is clicked, send user to Default
'End Sub
Protected Sub UploadPictureUI_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles UploadPictureUI.ItemInserting
'Reference the FileUpload control Dim UploadedFile As FileUpload = CType(UploadPictureUI.FindControl("UploadedFile"), FileUpload)

'Make sure a file has been successfully uploaded If UploadedFile.PostedFile Is Nothing OrElse String.IsNullOrEmpty(UploadedFile.PostedFile.FileName) OrElse UploadedFile.PostedFile.InputStream Is Nothing Then ShowErrorMessage("No file was uploaded. Please make sure that you've selected a file to upload.") e.Cancel = True Exit Sub End If 'Make sure we are dealing with a JPG or GIF file Dim extension As String = System.IO.Path.GetExtension(UploadedFile.PostedFile.FileName).ToLower() Dim MembershipFileType As String = Nothing Select Case extension Case ".gif"
MembershipFileType = "
Case "
.jpg", ".jpeg", ".jpe"
MembershipFileType = "
Case "
MembershipFileType = "
Case "
MembershipFileType = "
Case "
MembershipFileType = "

Case Else
'Invalid file type uploaded ShowErrorMessage("
Only GIF, JPG, and PNG and PDF AND DOC files can be uploaded to the picture album.")
e.Cancel = True
Exit Sub
End Select

'Specify the values for the MembershipFileType and ImageData parameters e.Values("
MembershipFileType") = MembershipFileType
MembershipFileLength") = UploadedFile.PostedFile.ContentLength

'Load FileUpload's InputStream into Byte array Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length) e.Values("
MembershipFileData") = imageBytes

End Sub


HERE IS THE DOWNLOAD CODE VIA A LINK -- does not download DOC files properly:

<!-- Link to File -->
                <asp:Repeater ID="RecentUploads" runat="server" DataSourceID="ContentListDataSource">
                    - <asp:HyperLink runat="server" Target="_blank" ID="lnkToPicture" NavigateUrl='<%# Eval("clubID", "~/NHSC/Admin/ShowDoc.aspx?clubID={0}") %>' Text='<%# Eval("MembershipFileName") %>'></asp:HyperLink>
                    - <i>uploaded <%#Eval("MembershipFileName", "{0:d}")%></i><br />
            <asp:SqlDataSource ID="RecentUploadsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT TOP 25 [clubID], [MembershipFileName] FROM [NHSC] ORDER BY [MembershipFileName] DESC">
            <!-- END Link to file -->



7/22/2008 6:02:33 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies

Similar Articles

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

Hi dude9er,

I never store .doc file directly into database. I usually upload files to a specific file path and store this filepath and filename into table. When I retrieve file, I get the filepath from table and display or download file by this path. Here is my upload file sample:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpload.aspx.cs" Inherits="FileUpload" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="C#" runat="server">
    private void btnUploadTheFile_Click(object Source, EventArgs evArgs)
        string strFileNameOnServer = txtServername.Value;
        string strBaseLocation = "c:\\temp\\";

        if ("" == strFileNameOnServer)
            txtOutput.InnerHtml = "Error - a file name must be specified.";

        if (uplTheFile.PostedFile != null)
                uplTheFile.PostedFile.SaveAs(strBaseLocation + strFileNameOnServer);
                txtOutput.InnerHtml = "File <b>" + strBaseLocation + strFileNameOnServer + "</b> uploaded successfully";

                FileInfo fi = new FileInfo(strBaseLocation + strFileNameOnServer);
                DateTime dt = new DateTime();
                dt = fi.CreationTime;
                long size = fi.Length;
                string sql = "insert into [file] values ('" + fi.FullName + "', '" + size + "', '" + dt.ToString() + "')";
                if (InsertToDB(sql) == 1)
            catch (Exception e)
                txtOutput.InnerHtml = "Error saving <b>" +
                  strBaseLocation + strFileNameOnServer + "</b><br>" + e.ToString();

    public int InsertToDB(string sql)
        SqlConnection conn = new SqlConnection(@"Server=(local)\SQLEXPRESS;Integrated Security=SSPI;Database=test;Persist Security Info=True");
        SqlCommand cmd = new SqlCommand(sql, conn);
        int result = cmd.ExecuteNonQuery();
        return result;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
  <form id="Form1" enctype="multipart/form-data" runat="server">
      <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="FileName"></asp:GridView>
      <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="select * from [file]" ConnectionString="<%$ ConnectionStrings:sql %>"></asp:SqlDataSource>
      <td>Select a File: </td>
      <td><input id="uplTheFile" type="file" runat="server" /></td>
      <td>Enter a Name: </td>
      <td><input id="txtServername" type="text" runat="server" /></td>
      <td><input type="button" id="btnUploadTheFile" value="Upload" onserverclick="btnUploadTheFile_Click" runat="server" /></td>
    <span id="txtOutput" runat="server" />


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
7/25/2008 7:12:38 AM

 HI Qin Dian Tang,


Thanks for the suggestion. I'm going to give it a try but I was wondering if you have this above code in VB instead of C#, or you can send me a link to a VB tutorial that uses the same concept. 

Thanks Again!

PS Sorry it took me so long to respond, this project got put on the back burner for a bit.

8/5/2008 5:10:58 PM

Hi dude9er,

This is vb code:

Private Sub btnUploadTheFile_Click(ByVal Source As Object, ByVal evArgs As EventArgs)
    Dim strFileNameOnServer As String = txtServername.Value
    Dim strBaseLocation As String = "c:\temp\"
    If "" = strFileNameOnServer Then
        txtOutput.InnerHtml = "Error - a file name must be specified."
    End If
    If uplTheFile.PostedFile IsNot Nothing Then
            uplTheFile.PostedFile.SaveAs(strBaseLocation + strFileNameOnServer)
            txtOutput.InnerHtml = "File <b>" + strBaseLocation + strFileNameOnServer + "</b> uploaded successfully"
            Dim fi As New FileInfo(strBaseLocation + strFileNameOnServer)
            Dim dt As New DateTime()
            dt = fi.CreationTime
            Dim size As Long = fi.Length
            Dim sql As String = "insert into [file] values ('" + fi.FullName + "', '" + size + "', '" + dt.ToString() + "')"
            If InsertToDB(sql) = 1 Then
            End If
        Catch e As Exception
            txtOutput.InnerHtml = "Error saving <b>" + strBaseLocation + strFileNameOnServer + "</b><br>" + e.ToString()
        End Try
    End If
End Sub

Public Function InsertToDB(ByVal sql As String) As Integer
    Dim conn As New SqlConnection("Server=(local)\SQLEXPRESS;Integrated Security=SSPI;Database=test;Persist Security Info=True")
    Dim cmd As New SqlCommand(sql, conn)
    Dim result As Integer = cmd.ExecuteNonQuery()
    Return result
End Function


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
8/6/2008 1:30:35 AM

 Hi Qin Dian Tang,   I'm getting this error and have scoured the net to find what is wrong. The files are saving in the DIR but the not in the DB.

System.InvalidCastException: Conversion from string "insert into [repProfileTbl] valu" to type 'Double' is not valid. ---> System.FormatException: Input string was not in a correct format. at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat) --- End of inner exception stack trace --- at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat) at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value) at ASP.fileupload_vb_aspx.btnUploadTheFile_Click(Object Source, EventArgs evArgs) in L:\TMX BU\My Documents\Websites External\TMX\Members Only Travel\HTML REPS\FileUpload_VB.aspx:line 27
 Here's line 27
Dim sql As String = "insert into [repProfileTbl] values ('" + fi.FullName + "', '" + size + "', '" + dt.ToString() + "')"
 Any ideas? 
8/8/2008 10:51:40 PM

Hi dude9er,

Yes, in my sample I store files in DIR and store file path into database. I think it is the usual way to deal with uploading files. The insert sql statement is only for my sample. You need to change to your own parameters or types. In my sample fi.FullName means the path of stored files, size means the size of file and dt.ToString() means storing date. They are all string type and nvchar in table. Maybe you have double or integer type in your table, so " ' " is not necessary.


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
8/11/2008 2:46:29 AM

 Hi Qin Dian Tang,


For the life of me I can not get this to work, nor can I find a good tutorial with this exact procedure. A shot in the dark, but are you able to put together a VB example for VWD that I can look at and how the database should look. I'm sorry for not understanding how to do this, but your help has been appreciated. Thank you for your time.

9/3/2008 4:00:36 PM

Web resources about - 4Guys Upload File includes PDF/DOC files - asp.net.presentation-controls

Wikipedia talk:Do not include the full text of lengthy primary sources - Wikipedia, the free encyclopedia ...
"Do not include copies of primary sources (specifically: text, maps, artworks and other useful images) in Wikipedia. If it is a large source, ...

Bing Redesign Includes Social Sidebar Column With More Facebook Integration
Microsoft introduced an update to its Bing search engine today that includes a sidebar column containing related information from users’ Facebook ...

Travis Kalanick - I thought I'd include a FB post I just... - Facebook
I thought I'd include a FB post I just did responding to a concern that Uber's SF service was decreasing in quality. _________________________ Hey... ...

Facebook News Feed changes include improvements for app developers
... is how much bigger stories and photos appear in the feed. The example below is full size. Then there’s the redesigned games feed, which includes ...

Amazon’s 12 best deals of the day include a virtual laser keyboard, a big 4K TV and more
... of deals each and every day to pick out some of the best bargains out there, and today we have some awesome deals for you to check out. Included ...

Will the growing Ted Cruz coalition eventually include the establishment? #Theyreconsideringit.
Will the growing Ted Cruz coalition eventually include the establishment? They're starting to think about it. by digby I wrote about Cruz again ...

Obama’s Gun-Control Plan Includes Gun-Ban For Some Social Security Beneficiaries
Obama's Gun-Control Plan Includes Gun-Ban For Some Social Security Beneficiaries

'Star Trek' turns 50 this year; celebrations include 'Ultimate Voyage' multimedia tour
Sci-fi juggernaut Star Trek turns 50 this year and amongst the celebrations is the "Ultimate Voyage Tour":This lavish production includes an ...

Bills' 2016 schedule includes six games against 2015 playoff teams, ranks as 10th-most difficult in NFL ...
To end a 16-year playoff drought, the Buffalo Bills will face teams next season that compiled a .520 winning percentage in 2015, going 133-123. ...

After internet outcry, 'Star Wars' Monopoly will include a Rey piece
... told Entertainment Weekly on Tuesday that the game was released in September, months before the movie came out, and Rey wasn’t included to avoid ...

Resources last updated: 1/11/2016 5:03:53 PM