Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1689
  • Last Modified:

How can I open files from a gridview hyperlink

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
rcon1con
Asked:
rcon1con
  • 18
  • 17
  • 2
1 Solution
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
Ok I will try this and get back to you. Thanks
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
rcon1conAuthor Commented:
Also
Name 'Request' is not declared

Thank you
0
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
The Asp.Net Page should inherit from System.Web.UI.Page.

Partial Class Students_Downloads Inherits System.Web.UI.Page
0
 
rcon1conAuthor Commented:
It says end of statement expected when i enter the code.
Partial Class Students_Downloads Inherits System.Web.UI.Page
0
 
GiftsonDJohnCommented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
GiftsonDJohnCommented:
Also please make sure that the url in the View hyperlink is correct.
0
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
sorry typo mistake.

remove the R. it is just fsfilename

FileDownload("C:\Users\Ronan\Documents\UploadedUserFiles\" & fsfilename, filename)
0
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
rcon1conAuthor Commented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
Hi,


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

Your code is correct. I'll go thru your code and will update you.
0
 
GiftsonDJohnCommented:
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
 
rcon1conAuthor Commented:
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
 
GiftsonDJohnCommented:
Can you debug and see whether any errors in runtime? whether the application reaches the code to execute?
0
 
rcon1conAuthor Commented:
No I get no errors. Is the code correct for the filedownload method?
0
 
spprivateCommented:
Did you not get any solution. GiftsonDJohn has worked so long with you in this?
0
 
GiftsonDJohnCommented:
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 18
  • 17
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now