Solved

How can I open files from a gridview hyperlink

Posted on 2009-04-14
39
1,664 Views
Last Modified: 2012-05-06
Hello

I have a gridview which displays the files being stored for individual users. So when a user logs in only their files are displayed in the gridview. The files are stored in a directory on my hard drive . How can I set the hyperlink called "View" to open the corresponding file in the directory

A picture of the gridview has been added as an attachement
<asp:GridView ID="gvFiles" runat="server" AllowPaging="True" 

        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="FileID" 

        DataSourceID="filesDataSource" BackColor="White" BorderColor="#DEDFDE" 

        BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" 

        GridLines="Vertical" Width="900px">

        <PagerSettings Mode="NextPrevious" />

        <RowStyle BackColor="#F7F7DE" />

        <Columns>

            <asp:HyperLinkField Text="View"  NavigateUrl='<%"C:\Users\Ronan\Documents\UploadedUserFiles\" & Eval("Title") %>'/>

            <asp:CommandField ShowEditButton="True" 

                DeleteImageUrl="~/Images/delete.gif" 

                EditImageUrl="~/Images/ebtn_addtolive.gif" />

            <asp:TemplateField HeaderText="CategoryID" SortExpression="CategoryID">

                <EditItemTemplate>

                    <asp:DropDownList ID="fileedit" runat="server" AppendDataBoundItems="True" 

                        SelectedValue='<%# Bind("CategoryID") %>' 

                        DataSourceID="categoriesDataSource" DataTextField="Name" 

                        DataValueField="CategoryID">

                        <asp:ListItem></asp:ListItem> 

                    </asp:DropDownList>

                    <asp:SqlDataSource ID="categoriesDataSource" runat="server" 

                        ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>" 

                        SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>

                </EditItemTemplate>

                <ItemTemplate>

                    <asp:DropDownList ID="filesreadonly" runat="server" 

                        DataSourceID="categoriesDataSource" DataTextField="Name" 

                        DataValueField="CategoryID" Enabled="False" 

                        SelectedValue='<%# Bind("CategoryID") %>'>

                    </asp:DropDownList>

                    <asp:SqlDataSource ID="categoriesDataSource" runat="server" 

                        ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>" 

                        SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>

                </ItemTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" >

            <ControlStyle Width="400px" />

            </asp:BoundField>

            <asp:BoundField DataField="Description" HeaderText="Description" 

                SortExpression="Description" />

            <asp:BoundField DataField="UploadedOn" HeaderText="Date Added" 

                SortExpression="UploadedOn" />

            <asp:CommandField ShowDeleteButton="True" />

        </Columns>

        <FooterStyle BackColor="#CCCC99" />

        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

        <AlternatingRowStyle BackColor="White" />

    </asp:GridView>
 
 
 

And here is the code from the code behind
 
 
 

Imports System.Data

Imports System.IO
 

Partial Class Students_Default4

    Inherits System.Web.UI.Page
 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()

        Dim UpPath As String

        Dim UpName As String

        UpPath = "C:\Users\Ronan\Documents\UploadedUserFiles"

        UpName = Dir(UpPath, vbDirectory)

        If (UpName = "") Then

            MkDir("C:\Users\Ronan\Documents\UploadedUserFiles")

        End If

    End Sub
 

    Protected Sub dvFileInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvFileInsert.ItemInserted

        If e.AffectedRows > 0 Then

            Dim results As DataView = CType(maxFileIDDatasource.Select(DataSourceSelectArguments.Empty), DataView)

            Dim fileIDJustAdded As Integer = CType(results(0)(0), Integer)

            Dim fileUpload As FileUpload = CType(dvFileInsert.FindControl("fileUpload"), FileUpload)
 

            Dim myFileName As String

            myFileName = fileUpload.PostedFile.FileName

            Dim c As String = System.IO.Path.GetFileName(myFileName)
 

            Try

                fileUpload.PostedFile.SaveAs("C:\Users\Ronan\Documents\UploadedUserFiles\" + c)
 

            Catch ex As Exception
 

            End Try

        End If

    End Sub
 
 

    Protected Sub dvFileInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvFileInsert.ItemInserting

        e.Values("UserID") = Membership.GetUser().ProviderUserKey

        e.Values("UploadedOn") = DateTime.Now
 
 

    End Sub
 

    Protected Sub gvFiles_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvFiles.RowDeleted

   

        Dim baseDirectory As String = Server.MapPath("~/UploadedUserFiles/")

        Dim filename As String = baseDirectory & e.Keys("Title")

        File.Delete(filename)
 

    End Sub
 
 

    Protected Sub gvFiles_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvFiles.RowUpdating

        e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
 

    End Sub
 

End Class

Open in new window

fhfh.jpg
0
Comment
Question by:rcon1con
  • 18
  • 17
  • 2
39 Comments
 
LVL 15

Expert Comment

by:spprivate
ID: 24141344
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24141390
Hi,

Create a new Web Form i.e. Download.aspx and on the code behind paste the code.

then change the View Hyperlink with

<asp:HyperLinkField Text="View"  NavigateUrl='<%"Download.aspx?FileName=" & Eval("Title") %>'/>

protected void Page_Load(object sender, EventArgs e)

{

    FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

}

private void FileDownload(string path)

    {

        FileInfo finfo = new FileInfo(path);        

        FileStream fstream = new FileStream(finfo.FullName, FileMode.Open);

 

        Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + finfo.Name + "\"");

 

        Response.Flush();

        long bytesToGo;

        int bytesRead;

        Byte[] buffer = new byte[1048576];

 

        bytesToGo = fstream.Length;

 

        while (bytesToGo > 0)

        {

            if (Response.IsClientConnected)

            {

                bytesRead = fstream.Read(buffer, 0, 1048576);

                Response.OutputStream.Write(buffer, 0, bytesRead);

                Response.Flush();

                bytesToGo -= bytesRead;

            }

            else

            {

                bytesToGo = -1;

            }

        }

 

        fstream.Close();

        Response.Flush();

    }

Open in new window

0
 

Author Comment

by:rcon1con
ID: 24141691
Ok I will try this and get back to you. Thanks
0
 

Author Comment

by:rcon1con
ID: 24145591
Hello again. I forgot to mention that I am coding in VB. I am pretty new to ASP.NET and I am not to sure how to covert the code from c# to vb. Is it possible if you could post me the same solution in vb.

Thank you
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24145835
Here is the VB.net equivalent for C#
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

End Sub

Private Sub FileDownload(ByVal path As String)

    Dim finfo As New FileInfo(path)

    Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

    

    Response.ContentType = "application/octet-stream"

    Response.AddHeader("Content-Disposition", "attachment; filename=""" & finfo.Name & """")

    

    Response.Flush()

    Dim bytesToGo As Long

    Dim bytesRead As Integer

    Dim buffer As [Byte]() = New Byte(1048575) {}

    

    bytesToGo = fstream.Length

    

    While bytesToGo > 0

        If Response.IsClientConnected Then

            bytesRead = fstream.Read(buffer, 0, 1048576)

            Response.OutputStream.Write(buffer, 0, bytesRead)

            Response.Flush()

            bytesToGo -= bytesRead

        Else

            bytesToGo = -1

        End If

    End While

    

    fstream.Close()

    Response.Flush()

End Sub

Open in new window

0
 

Author Comment

by:rcon1con
ID: 24145982
Ok I've pasted the code into the code behind for download.aspx and I have changed the view hyperlink but in the code behind a few errors appear. The errors are as follows:

Name 'Response' is not declared
type FileInfo is not defined
type FileStream is not defined

How should these be resolved
Thank you
0
 

Author Comment

by:rcon1con
ID: 24145987
Also
Name 'Request' is not declared

Thank you
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146015
Please make sure that the following imports are there in Download.aspx.vb

Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.IO
0
 

Author Comment

by:rcon1con
ID: 24146061
are there any other imports missing because response and request are still not being declared. Here is the code so far.

Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.IO


Partial Class Students_Downloads
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

    End Sub

    Private Sub FileDownload(ByVal path As String)
        Dim finfo As New FileInfo(path)
        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

        Response.ContentType = "application/octet-stream"
        Response.AddHeader("Content-Disposition", "attachment; filename=""" & finfo.Name & """")

        Response.Flush()

        Dim bytesToGo As Long
        Dim bytesRead As Integer
        Dim buffer As [Byte]() = New Byte(1048575) {}

        bytesToGo = fstream.Length

        While bytesToGo > 0
            If Response.IsClientConnected Then
                bytesRead = fstream.Read(buffer, 0, 1048576)
                Response.OutputStream.Write(buffer, 0, bytesRead)
                Response.Flush()
                bytesToGo -= bytesRead
            Else
                bytesToGo = -1
            End If
        End While

        fstream.Close()
        Response.Flush()
    End Sub


End Class
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146088
The Asp.Net Page should inherit from System.Web.UI.Page.

Partial Class Students_Downloads Inherits System.Web.UI.Page
0
 

Author Comment

by:rcon1con
ID: 24146121
It says end of statement expected when i enter the code.
Partial Class Students_Downloads Inherits System.Web.UI.Page
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146148
Please try this.
Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.HtmlControls

Imports System.IO
 

Partial Class Students_Downloads

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        

        

        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

    End Sub

    

    Private Sub FileDownload(ByVal path As String)

        Dim finfo As New FileInfo(path)

        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

        

        Response.ContentType = "application/octet-stream"

        Response.AddHeader("Content-Disposition", "attachment; filename=""" & finfo.Name & """")

        

        Response.Flush()

        

        Dim bytesToGo As Long = 0

        Dim bytesRead As Integer = 0

        Dim buffer As [Byte]() = New Byte(1048575) {}

        

        bytesToGo = fstream.Length

        

        While bytesToGo > 0

            If Response.IsClientConnected Then

                bytesRead = fstream.Read(buffer, 0, 1048576)

                Response.OutputStream.Write(buffer, 0, bytesRead)

                Response.Flush()

                bytesToGo -= bytesRead

            Else

                bytesToGo = -1

            End If

        End While

        

        fstream.Close()

        Response.Flush()

    End Sub

    

    

End Class

Open in new window

0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146150
Please use this
Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.HtmlControls

Imports System.IO
 

Public Partial Class Students_Downloads

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        

        

        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

    End Sub

    

    Private Sub FileDownload(ByVal path As String)

        Dim finfo As New FileInfo(path)

        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

        

        Response.ContentType = "application/octet-stream"

        Response.AddHeader("Content-Disposition", "attachment; filename=""" & finfo.Name & """")

        

        Response.Flush()

        

        Dim bytesToGo As Long = 0

        Dim bytesRead As Integer = 0

        Dim buffer As [Byte]() = New Byte(1048575) {}

        

        bytesToGo = fstream.Length

        

        While bytesToGo > 0

            If Response.IsClientConnected Then

                bytesRead = fstream.Read(buffer, 0, 1048576)

                Response.OutputStream.Write(buffer, 0, bytesRead)

                Response.Flush()

                bytesToGo -= bytesRead

            Else

                bytesToGo = -1

            End If

        End While

        

        fstream.Close()

        Response.Flush()

    End Sub

    

    

End Class

Open in new window

0
 

Author Comment

by:rcon1con
ID: 24146177
Ok there are no longer any errors with the downloads.aspx.vb code behind. When I run the page with gridview in the browser and click on the view button, nothing happens.

here is the gridview code

<asp:GridView ID="gvFiles" runat="server" AllowPaging="True"
        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="FileID"
        DataSourceID="filesDataSource" BackColor="White" BorderColor="#DEDFDE"
        BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
        GridLines="Vertical" Width="800px" style="margin-left:50px;margin-top:20px">
        <PagerSettings Mode="NextPrevious" />
        <RowStyle BackColor="#F7F7DE" />
        <Columns>
            <asp:HyperLinkField Text="View"  NavigateUrl='<%"Download.aspx?FileName=" & Eval("Title") %>'/>
            <asp:CommandField ShowEditButton="True"
                DeleteImageUrl="~/Images/delete.gif"
                EditImageUrl="~/Images/edit.gif" ButtonType="Image" />
            <asp:TemplateField HeaderText="CategoryID" SortExpression="CategoryID">
                <EditItemTemplate>
                    <asp:DropDownList ID="fileedit" runat="server" AppendDataBoundItems="True"
                        SelectedValue='<%# Bind("CategoryID") %>'
                        DataSourceID="categoriesDataSource" DataTextField="Name"
                        DataValueField="CategoryID">
                        <asp:ListItem></asp:ListItem>
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="categoriesDataSource" runat="server"
                        ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>"
                        SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:DropDownList ID="filesreadonly" runat="server"
                        DataSourceID="categoriesDataSource" DataTextField="Name"
                        DataValueField="CategoryID" Enabled="False"
                        SelectedValue='<%# Bind("CategoryID") %>'>
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="categoriesDataSource" runat="server"
                        ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>"
                        SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" >
            <ControlStyle Width="400px" />
            </asp:BoundField>
            <asp:BoundField DataField="Description" HeaderText="Description"
                SortExpression="Description" />
            <asp:BoundField DataField="UploadedOn" HeaderText="Date Added"
                SortExpression="UploadedOn" />
            <asp:CommandField ShowDeleteButton="True" ButtonType="Image"
                DeleteImageUrl="~/Images/delete.gif" />
        </Columns>
        <FooterStyle BackColor="#CCCC99" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146233
Hi,

You have Students_Default4.aspx and you are loading the grid with view link and other details.

Do you have Download.aspx or Students_Downloads.aspx? If you have created the page Students_Downloads.aspx for downloading the files you have to change the NavigateUrl value to  <asp:HyperLinkField Text="View"  NavigateUrl='<%"Students_Downloads.aspx?FileName=" & Eval("Title") %>'/>
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146238
Also please make sure that the url in the View hyperlink is correct.
0
 

Author Comment

by:rcon1con
ID: 24146303
I have made the changes to the hyperlink to become  <asp:HyperLinkField Text="View"  NavigateUrl='<%"Students_Downloads.aspx?FileName=" & Eval("Title") %>'/> and I have checked that the url in the view hyperlink is correct. Nothing happens whenever I click on the view link in the browser.
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146323
Sorry. One more correction has to be made.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

I am a C# guy so making a little mess.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:rcon1con
ID: 24146384
Where is that correction made?

I think their might be a problem with how it finds and opens the file. I have posted another picture of my gridview and the directory it is uploading to. As you can see the name of the file is different from the title that it has been given when uploaded. Im guessing the file name has to appended some way to the name of the directory so it can be opened?

Thank you


aaaa.jpg
dddd.jpg
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146614
The change has to be implemented in Student_Downloads.aspx.vb.

Are you storing the filename anywhere in the database?
Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.HtmlControls

Imports System.IO

 

Public Partial Class Students_Downloads

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        

        

        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & Request("FileName"))

    End Sub

    

    Private Sub FileDownload(ByVal path As String)

        Dim finfo As New FileInfo(path)

        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

        

        Response.ContentType = "application/octet-stream"

        Response.AddHeader("Content-Disposition", "attachment; filename=""" & finfo.Name & """")

        

        Response.Flush()

        

        Dim bytesToGo As Long = 0

        Dim bytesRead As Integer = 0

        Dim buffer As [Byte]() = New Byte(1048575) {}

        

        bytesToGo = fstream.Length

        

        While bytesToGo > 0

            If Response.IsClientConnected Then

                bytesRead = fstream.Read(buffer, 0, 1048576)

                Response.OutputStream.Write(buffer, 0, bytesRead)

                Response.Flush()

                bytesToGo -= bytesRead

            Else

                bytesToGo = -1

            End If

        End While

        

        fstream.Close()

        Response.Flush()

    End Sub

    

    

End Class

Open in new window

0
 

Author Comment

by:rcon1con
ID: 24146655
The filename is not stored in the database. Is it advisable to do this? If so how can the file names be stored everytime a person uploads a file?

Here is how my database table for files looks.
qqq.jpg
www.jpg
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146893
Yes it is mandatory to store the filename whenever the user uploads the file. But there will be problem if the user uploads file with the name of the file which already exists on the page. So it is advised that You store the file name into the database. But while storing the file into the File System (Directory) use the primary key value of the entry. i.e. if a user uploads a file (ccs32.pdf), insert the values (file name, title, description etc...) into the database, get the primary key value back from the database, for example 1, save the file ccs32.pdf as 1.pdf into the File System.

When anyone tries to download the file, you can easily locate the file 1.pdf from the file system. Set the file name while downloading the file. I have made the changes in the download page.

The hyperlink will change to

<asp:HyperLinkField Text="View"  NavigateUrl='<%"Download.aspx?FileID=" & Eval("FileID") %>'/>

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.HtmlControls

Imports System.IO

 

Public Partial Class Students_Downloads

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        Dim SqlCon As New SqlConnection("<SqlConnection string>")

        Dim SqlCmd As New SqlCommand("Select FileName from UserFiles where FileID=" & Request("FileID"))

        Dim filename As String = SqlCmd.ExecuteScalar().ToString()
 

        Dim finfo As New FileInfo(filename)

        Dim fsfilename As String = Request("FileID") + finfo.Extension
 

        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & R fsfilename, filename)

    End Sub

    

    Private Sub FileDownload(ByVal path As String, ByVal filename As String)

        Dim finfo As New FileInfo(path)

        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)

        

        Response.ContentType = "application/octet-stream"

        Response.AddHeader("Content-Disposition", "attachment; filename=""" & filename & """")

        

        Response.Flush()

        

        Dim bytesToGo As Long = 0

        Dim bytesRead As Integer = 0

        Dim buffer As [Byte]() = New Byte(1048575) {}

        

        bytesToGo = fstream.Length

        

        While bytesToGo > 0

            If Response.IsClientConnected Then

                bytesRead = fstream.Read(buffer, 0, 1048576)

                Response.OutputStream.Write(buffer, 0, bytesRead)

                Response.Flush()

                bytesToGo -= bytesRead

            Else

                bytesToGo = -1

            End If

        End While

        

        fstream.Close()

        Response.Flush()

    End Sub

    

    

End Class

Open in new window

0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24146905
A small correction

On the Page_Load function of Student_Downloads.aspx.vb, after creating SqlConnection object, include

SqlCon.Open();

and after the SqlCmd.ExecuteScalar function, include

SqlCon.Close();
0
 

Author Comment

by:rcon1con
ID: 24146993
I get errors with this line of code
17:   FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & R fsfilename, filename)

is the R meant to be "Request" or is it simply a typo?
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24147040
sorry typo mistake.

remove the R. it is just fsfilename

FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & fsfilename, filename)
0
 

Author Comment

by:rcon1con
ID: 24147181
How exactly do you extract the filename from the upload bar to insert into the database? Below is the code of my files sqldatasource. I have changed it slighlty to be inserting the value @filename

<asp:SqlDataSource ID="filesDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString3 %>"
        DeleteCommand="DELETE FROM [Files] WHERE [FileID] = @FileID"
        InsertCommand="INSERT INTO [Files] ([UserID],[filename], [CategoryID], [Title], [Description], [UploadedOn]) VALUES (@UserID, @filename, @CategoryID, @Title, @Description, @UploadedOn)"
        SelectCommand="SELECT * FROM [Files] WHERE ([UserID] = @UserID) ORDER BY [UploadedOn] DESC"
        UpdateCommand="UPDATE [Files] SET [UserID] = @UserID, [CategoryID] = @CategoryID, [Title] = @Title, [Description] = @Description, [UploadedOn] = @UploadedOn WHERE [FileID] = @FileID">
        <SelectParameters>
            <asp:ControlParameter ControlID="UserIdValue" Name="UserID" PropertyName="Text"/>
        </SelectParameters>
        <DeleteParameters>
            <asp:Parameter Name="FileID" Type="Int32" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="UserID"/>
            <asp:Parameter Name="CategoryID" Type="Int32" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="UploadedOn" Type="DateTime" />
            <asp:Parameter Name="FileID" Type="Int32" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="UserID"/>
             <asp:Parameter Name="filename" Type="String"/>
            <asp:Parameter Name="CategoryID" Type="Int32" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="UploadedOn" Type="DateTime" />
        </InsertParameters>
    </asp:SqlDataSource>


This is how I am inserting the value of the logged in user to the files database table
Protected Sub dvFileInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvFileInsert.ItemInserting
        e.Values("UserID") = Membership.GetUser().ProviderUserKey
        e.Values("UploadedOn") = DateTime.Now
    End Sub
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24147385
You can get the actual filename from FileUpload object.

Dim originalfilename As String = fileUpload.PostedFile.FileName
Dim finfo As New FileInfo(originalfilename)
Dim alteredfilename As String = FileID + finfo.Extension

The FileID is the primary key value you get after inserting the row into the database. The you can use

fileUpload.PostedFile.SaveAs("C:\Users\Ronan\Documents\UploadedUserFiles\" + alteredfilename)

to save the file into file system.
0
 

Author Comment

by:rcon1con
ID: 24147568
Im not quite sure what you mean. Can you show me how to alter the code so that I am instantiating the variable FileID with the value of FileID from the database. The code below is for the codebehind of the gridview. Thankyou

Imports System.Data
Imports System.IO

Partial Class Students_Default4
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
        Dim UpPath As String
        Dim UpName As String
        UpPath = "C:\Users\Ronan\Documents\UploadedUserFiles"
        UpName = Dir(UpPath, vbDirectory)
        If (UpName = "") Then
            MkDir("C:\Users\Ronan\Documents\UploadedUserFiles")
        End If
    End Sub

    Protected Sub dvFileInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvFileInsert.ItemInserted
        If e.AffectedRows > 0 Then
            Dim results As DataView = CType(maxFileIDDatasource.Select(DataSourceSelectArguments.Empty), DataView)
            Dim fileIDJustAdded As Integer = CType(results(0)(0), Integer)
            Dim fileUpload As FileUpload = CType(dvFileInsert.FindControl("fileUpload"), FileUpload)

            Dim myFileName As String
            myFileName = fileUpload.PostedFile.FileName
            Dim c As String = System.IO.Path.GetFileName(myFileName)

            Dim originalfilename As String = fileUpload.PostedFile.FileName
            Dim finfo As New FileInfo(originalfilename)
            Dim alteredfilename As String = fileIDJustAdded + finfo.Extension


            Try
                fileUpload.PostedFile.SaveAs("C:\Users\Ronan\Documents\UploadedUserFiles\" + alteredfilename)

            Catch ex As Exception

            End Try
        End If
    End Sub


    Protected Sub dvFileInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvFileInsert.ItemInserting
        e.Values("UserID") = Membership.GetUser().ProviderUserKey
        e.Values("UploadedOn") = DateTime.Now
       


    End Sub

    Protected Sub gvFiles_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvFiles.RowDeleted

    End Sub


    Protected Sub gvFiles_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvFiles.RowUpdating
        e.NewValues("UserId") = Membership.GetUser().ProviderUserKey

    End Sub
End Class
0
 

Author Comment

by:rcon1con
ID: 24147893
In other words I want to be able to do something like this to put th filename into the database

e.Values("filename") = originalfilename

because I get the error

Cannot insert the value NULL into column 'filename', table 'C:\USERS\RONAN\DOCUMENTS\SOFTWARE ENGINEERING PROJECT\VLE\APP_DATA\ASPNETDB.MDF.dbo.Files'; column does not allow nulls. INSERT fails.
The statement has been terminated.
0
 

Author Comment

by:rcon1con
ID: 24192449
I want to be able to insert filename into the database somehow. Can someonetake a look at the code and point me in the right direction. I tried using a sql cmd which was something like this.
dim statement as string("INSERT INTO Files(filename) VALUES('" & FileUpload.PostedFile.Filename & "').

Thank you
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24193909
Hi,


>>>"INSERT INTO Files(filename) VALUES('" & FileUpload.PostedFile.Filename & "')"

Your code is correct. I'll go thru your code and will update you.
0
 
LVL 14

Accepted Solution

by:
GiftsonDJohn earned 500 total points
ID: 24194392
Have you tried this

 Protected Sub gvFiles_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvFiles.RowUpdating
        Dim fileUpload As FileUpload = CType(dvFileInsert.Rows[dvFileInsert.EditIndex].FindControl("fileUpload"), FileUpload)
        e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
        e.NewValues("filename") = fileUpload.PostedFile.FileName
 End Sub

Make sure that while selecting FileUpload control you are using

Dim fileUpload As FileUpload = CType(dvFileInsert.Rows[dvFileInsert.EditIndex].FindControl("fileUpload"), FileUpload)

to get any control from that specific row.
0
 

Author Comment

by:rcon1con
ID: 24194527
Yes that works. The filename is in the database as just the name and the extension i.e "file.doc". There is no path before it. When I click the view button to open the file now nothing happens. This is the code I am using to download the file. Is there anything you can see that is wrong with it?

Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.IO
 
Public Partial Class Students_Downloads
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim SqlCon As New SqlConnection("<SqlConnection string>")
        Dim SqlCmd As New SqlCommand("Select FileName from UserFiles where FileID=" & Request("FileID"))
        Dim filename As String = SqlCmd.ExecuteScalar().ToString()
 
        Dim finfo As New FileInfo(filename)
        Dim fsfilename As String = Request("FileID") + finfo.Extension
 
        FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & fsfilename, filename)
    End Sub
   
    Private Sub FileDownload(ByVal path As String, ByVal filename As String)
        Dim finfo As New FileInfo(path)
        Dim fstream As New FileStream(finfo.FullName, FileMode.Open)
       
        Response.ContentType = "application/octet-stream"
        Response.AddHeader("Content-Disposition", "attachment; filename=""" & filename & """")
       
        Response.Flush()
       
        Dim bytesToGo As Long = 0
        Dim bytesRead As Integer = 0
        Dim buffer As [Byte]() = New Byte(1048575) {}
       
        bytesToGo = fstream.Length
       
        While bytesToGo > 0
            If Response.IsClientConnected Then
                bytesRead = fstream.Read(buffer, 0, 1048576)
                Response.OutputStream.Write(buffer, 0, bytesRead)
                Response.Flush()
                bytesToGo -= bytesRead
            Else
                bytesToGo = -1
            End If
        End While
       
        fstream.Close()
        Response.Flush()
    End Sub
   
   
End Class


0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24194751
Can you debug and see whether any errors in runtime? whether the application reaches the code to execute?
0
 

Author Comment

by:rcon1con
ID: 24195381
No I get no errors. Is the code correct for the filedownload method?
0
 
LVL 15

Expert Comment

by:spprivate
ID: 24200067
Did you not get any solution. GiftsonDJohn has worked so long with you in this?
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24201338
Thanks spprivate.

hi rcon1con, The code for filedownload method is correct. It is also posted in EE thread and it is accepted by lot of users. Just make sure that you are calling the page correctly.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now