locked
Save As dialog for text file RRS feed

  • Question

  • User-1767698477 posted

    I want to be able to allow a user at my site to download a text file to their local machine. They should be presented with a save as dialog. I found this code here below. My question is how do I get the filename and path to this sub? I tried a couple of hyperlinks, but they are not working for me. They don't do anything when clicked and the browser doesn't allow the file to open up and be saved. I'm using a gridview. Should I create a button and code each button with a path to the file and a filename? Is it possible to set these as command args in the code behind so when the user clicks the button these paramaters are passed into this sub here and the user is served up a save as dialog?

    Public Sub DownloadFile()
            Dim FileName As String = ""
            Dim FilePath As String = ""
            'Dim FilePath As String = AppDomain.CurrentDomain.BaseDirectory & "/App_Data/Uploads/" + FileName
            Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
            response.ClearContent()
            response.Clear()
            response.ContentType = "text/plain"
            response.AddHeader("Content-Disposition", "attachment; filename=" & FileName & ";")
            response.TransmitFile(FilePath)
            response.Flush()
            response.[End]()
        End Sub

    Sunday, January 3, 2021 3:34 AM

Answers

  • User-1716253493 posted

    Get the file path, then read it.  Use hyplinkbutton cllick event

    Dim fullpath As String = System.IO.Path.GetFullPath("~/App_Data/Uploads/" & FileName)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 3:01 AM
  • User-1330468790 posted

    Hi sking,

     

    My question is how do I get the filename and path to this sub?

    There are two ways to pass parameters from a grid view row to the server side

    1. button's 'CommandArgument' property (Either LinkButton or Button should be working).
    2. HiddenField control with its 'Value' property.

     

    Should I create a button and code each button with a path to the file and a filename?

    As I mentioned above, yes, you should create a button for each grid view row. Fortunately, you could directly use 'Template' of the GridView control to add buttons and hence you don't need to do repetitive works.

     

    Is it possible to set these as command args in the code behind so when the user clicks the button these paramaters are passed into this sub here and the user is served up a save as dialog?

    For the end of your question, you mentioned a 'save-as' dialog. I am afraid that it is not possible to present a save-as dialog via Backend codes.

    Actually, it is a browser behavior that you could let the user to turn on the feature in browsers.

    To turn this feature on and take control over where your downloads go, follow these steps:

    • Click the menu icon in Chrome and click Settings.
    • Scroll down and click “Show advances settings...”
    • Scroll to the Downloads section.
    • Click the “Ask where to save each file before downloading” toggle.

     

    Another thing is that you have to store the paths and names of files in database so that you could attach those paths and names to the controls in grid view.

    More details, you could refer to below codes in VB.

    aspx (with javascript function 'confirm'):

     <form id="form1" runat="server">
            <div>
                 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="ID" />
                        <asp:TemplateField HeaderText="Image">
                            <ItemTemplate>
                                <asp:Image ID="image1" runat="server" ImageUrl='<%#Eval("card") %>' Width="100" Height="100" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Card Title">
                            <ItemTemplate>
                                <asp:Label ID="label1" runat="server" Text='<%# Eval("card_title") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                       <asp:TemplateField HeaderText="Content">
                            <ItemTemplate>
                                <asp:Label ID="label2" runat="server" Text='<%# Eval("content") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                         <asp:TemplateField HeaderText="Download">
                            <ItemTemplate>
                                <asp:HiddenField ID="hf_title" runat="server" Value='<%#Eval("card_title") %>' />
                                <asp:Button ID="downloadBtn" runat="server" CommandName="Download" CommandArgument='<%#Eval("card") %>' OnClientClick='<%#"return confirm(""Do you want To download file " & Eval("card_title") & """)" %>' Text="Download" />
                                 <asp:LinkButton ID="downloadLkBtn" runat="server" CommandName="Download" CommandArgument='<%#Eval("card") %>' OnClientClick='<%#"return confirm(""Do you want to download file " & Eval("card_title") & """)" %>' Text="Download"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>

    Code behind:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                BindGridView()
            End If
        End Sub
    
        Public Sub BindGridView()
            Dim sql As String = "SELECT [Id], [card], [card_title],[content] FROM [blog]"
            GridView1.DataSource = SelectFromDatabase(sql, Nothing)
            GridView1.DataBind()
        End Sub
    
        Public Shared Function SelectFromDatabase(ByVal sql As String, ByVal parameters As SqlParameter()) As DataTable
            Dim constr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    
            Using con As SqlConnection = New SqlConnection(constr)
    
                Using cmd As SqlCommand = New SqlCommand(sql, con)
    
                    If parameters IsNot Nothing Then
                        cmd.Parameters.AddRange(parameters)
                    End If
    
                    Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                        Dim dt As DataTable = New DataTable()
                        sda.Fill(dt)
                        Return dt
                    End Using
                End Using
            End Using
        End Function
    
        Public Sub DownloadFile(ByVal FileName As String, ByVal FilePath As String)
            If Not String.IsNullOrEmpty(FileName) AndAlso Not String.IsNullOrEmpty(FilePath) Then
                Dim response As HttpResponse = System.Web.HttpContext.Current.Response
                response.ClearContent()
                response.Clear()
                response.ContentType = "text/plain"
                response.AddHeader("Content-Disposition", "attachment; filename=" & FileName & ";")
                response.TransmitFile(FilePath)
                response.Flush()
                response.[End]()
            End If
        End Sub
    
        Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
            If e.CommandName = "Download" Then
                Dim row As GridViewRow = CType((CType(e.CommandSource, Control)).NamingContainer, GridViewRow)
                Dim hf As HiddenField = CType(row.FindControl("hf_title"), HiddenField)
                Dim filePath As String = e.CommandArgument.ToString()
                Dim fileName As String = hf.Value
                DownloadFile(fileName, filePath)
            End If
        End Sub

    Data:

     

    Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 4:01 AM

All replies

  • User-1716253493 posted

    Get the file path, then read it.  Use hyplinkbutton cllick event

    Dim fullpath As String = System.IO.Path.GetFullPath("~/App_Data/Uploads/" & FileName)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 3:01 AM
  • User-1330468790 posted

    Hi sking,

     

    My question is how do I get the filename and path to this sub?

    There are two ways to pass parameters from a grid view row to the server side

    1. button's 'CommandArgument' property (Either LinkButton or Button should be working).
    2. HiddenField control with its 'Value' property.

     

    Should I create a button and code each button with a path to the file and a filename?

    As I mentioned above, yes, you should create a button for each grid view row. Fortunately, you could directly use 'Template' of the GridView control to add buttons and hence you don't need to do repetitive works.

     

    Is it possible to set these as command args in the code behind so when the user clicks the button these paramaters are passed into this sub here and the user is served up a save as dialog?

    For the end of your question, you mentioned a 'save-as' dialog. I am afraid that it is not possible to present a save-as dialog via Backend codes.

    Actually, it is a browser behavior that you could let the user to turn on the feature in browsers.

    To turn this feature on and take control over where your downloads go, follow these steps:

    • Click the menu icon in Chrome and click Settings.
    • Scroll down and click “Show advances settings...”
    • Scroll to the Downloads section.
    • Click the “Ask where to save each file before downloading” toggle.

     

    Another thing is that you have to store the paths and names of files in database so that you could attach those paths and names to the controls in grid view.

    More details, you could refer to below codes in VB.

    aspx (with javascript function 'confirm'):

     <form id="form1" runat="server">
            <div>
                 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="ID" />
                        <asp:TemplateField HeaderText="Image">
                            <ItemTemplate>
                                <asp:Image ID="image1" runat="server" ImageUrl='<%#Eval("card") %>' Width="100" Height="100" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Card Title">
                            <ItemTemplate>
                                <asp:Label ID="label1" runat="server" Text='<%# Eval("card_title") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                       <asp:TemplateField HeaderText="Content">
                            <ItemTemplate>
                                <asp:Label ID="label2" runat="server" Text='<%# Eval("content") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                         <asp:TemplateField HeaderText="Download">
                            <ItemTemplate>
                                <asp:HiddenField ID="hf_title" runat="server" Value='<%#Eval("card_title") %>' />
                                <asp:Button ID="downloadBtn" runat="server" CommandName="Download" CommandArgument='<%#Eval("card") %>' OnClientClick='<%#"return confirm(""Do you want To download file " & Eval("card_title") & """)" %>' Text="Download" />
                                 <asp:LinkButton ID="downloadLkBtn" runat="server" CommandName="Download" CommandArgument='<%#Eval("card") %>' OnClientClick='<%#"return confirm(""Do you want to download file " & Eval("card_title") & """)" %>' Text="Download"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>

    Code behind:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                BindGridView()
            End If
        End Sub
    
        Public Sub BindGridView()
            Dim sql As String = "SELECT [Id], [card], [card_title],[content] FROM [blog]"
            GridView1.DataSource = SelectFromDatabase(sql, Nothing)
            GridView1.DataBind()
        End Sub
    
        Public Shared Function SelectFromDatabase(ByVal sql As String, ByVal parameters As SqlParameter()) As DataTable
            Dim constr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    
            Using con As SqlConnection = New SqlConnection(constr)
    
                Using cmd As SqlCommand = New SqlCommand(sql, con)
    
                    If parameters IsNot Nothing Then
                        cmd.Parameters.AddRange(parameters)
                    End If
    
                    Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                        Dim dt As DataTable = New DataTable()
                        sda.Fill(dt)
                        Return dt
                    End Using
                End Using
            End Using
        End Function
    
        Public Sub DownloadFile(ByVal FileName As String, ByVal FilePath As String)
            If Not String.IsNullOrEmpty(FileName) AndAlso Not String.IsNullOrEmpty(FilePath) Then
                Dim response As HttpResponse = System.Web.HttpContext.Current.Response
                response.ClearContent()
                response.Clear()
                response.ContentType = "text/plain"
                response.AddHeader("Content-Disposition", "attachment; filename=" & FileName & ";")
                response.TransmitFile(FilePath)
                response.Flush()
                response.[End]()
            End If
        End Sub
    
        Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
            If e.CommandName = "Download" Then
                Dim row As GridViewRow = CType((CType(e.CommandSource, Control)).NamingContainer, GridViewRow)
                Dim hf As HiddenField = CType(row.FindControl("hf_title"), HiddenField)
                Dim filePath As String = e.CommandArgument.ToString()
                Dim fileName As String = hf.Value
                DownloadFile(fileName, filePath)
            End If
        End Sub

    Data:

     

    Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 4:01 AM