如何从字符串创建文本文件并在ASP.NET中打开新选项卡?

huangapple go评论45阅读模式
英文:

How to create a text file from a string and open it in new tab in asp.net?

问题

我想要在 ASPX 页面的按钮点击时,从字符串创建一个文本文件,并将其发送到浏览器的新标签页。该文件必须即时创建,不应存储在服务器上。

目前,我可以通过将文件附加到 HTTP 响应中并将该响应发送到浏览器来在同一标签页上发送文件。

英文:

I want to create a text file from a string and send it to browser's new tab on a button click in aspx page. The file must be created on the fly and should not be stored anywhere on server.

Currently, I am able to send the file on the same tab by attaching the file in the http response and sending that response to browser.

答案1

得分: 1

不幸的是,由于弹出窗口阻止程序,创建一个标签页在这些日子里确实行不通。

但是,您可以在同一页上,通过按钮点击,然后“模拟”用户导航到一个简单的文本文档,就好像用户真的导航到了它一样。

这段代码将有效:

Protected Sub cmdJump_Click(sender As Object, e As EventArgs)

    Dim strBuf =
        "文本的第一行" & vbCrLf &
        "文本的第二行" & vbCrLf &
        "文本的第三行"

    Dim strFakeFileName As String = "mytext.txt"
    Dim strConType = MimeMapping.GetMimeMapping(strFakeFileName)

    Response.Clear()
    Response.ContentType = strConType
    Response.AppendHeader("Content-Length", strBuf.Length)
    Response.AppendHeader("Content-Disposition", "inline; filename=" & strFakeFileName)
    Response.Write(strBuf)
    Response.End()

End Sub

如上所述,这将在当前页面上发生。用户可以点击浏览器的返回按钮。

然而,打开一个新的标签页?现代浏览器几乎不允许这样做。

英文:

unfortantly, due to popup blockers, creating a tab really not going to work these days.

However, you can on the same page, say a button click, and then "fake" the same thing as if the user did navigate to a simple text document.

This code will work:

Protected Sub cmdJump_Click(sender As Object, e As EventArgs)

    Dim strBuf =
        "First line of text" & vbCrLf &
        "Seond line of text" & vbCrLf &
        "Third line of text"

    Dim strFakeFileName As String = "mytext.txt"
    Dim strConType = MimeMapping.GetMimeMapping(strFakeFileName)

    Response.Clear()
    Response.ContentType = strConType
    Response.AppendHeader("Content-Length", strBuf.Length)
    Response.AppendHeader("Content-Disposition", "inline; filename=" & strFakeFileName)
    Response.Write(strBuf)
    Response.End()

End Sub

As noted, this will occur on the current page. User can hit back button.

However, opening a new tab? Modern browsers just don't allow this with much success.

huangapple
  • 本文由 发表于 2023年2月14日 01:08:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定