Http 下载文件时如何使客户端打开“保存文件”对话框

Http 下载文件时如何使客户端打开“保存文件”对话框,http,go,web,download,Http,Go,Web,Download,我希望浏览器显示或打开“文件保存”对话框,以保存用户单击“下载文件”按钮时发送的文件 我要下载的服务器端代码: func Download(w http.ResponseWriter, r *http.Request) { url := "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png" timeout := time.Duration(5) * time.Second transport := &h

我希望浏览器显示或打开“文件保存”对话框,以保存用户单击“下载文件”按钮时发送的文件

我要下载的服务器端代码:

func Download(w http.ResponseWriter, r *http.Request) {
    url := "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png"

    timeout := time.Duration(5) * time.Second
    transport := &http.Transport{
        ResponseHeaderTimeout: timeout,
        Dial: func(network, addr string) (net.Conn, error) {
            return net.DialTimeout(network, addr, timeout)
        },
        DisableKeepAlives: true,
    }
    client := &http.Client{
        Transport: transport,
    }
    resp, err := client.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()

    //copy the relevant headers. If you want to preserve the downloaded file name, extract it with go's url parser.
    w.Header().Set("Content-Disposition", "form-data; filename=Wiki.png")
    w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
    w.Header().Set("Content-Length", r.Header.Get("Content-Length"))
    //dialog.File().Filter("XML files", "xml").Title("Export to XML").Save()
    //stream the body to the client without fully loading it into memory
    io.Copy(w, resp.Body)
}

如果您希望将响应保存在客户端,请使用
“附件”
内容处置类型。详情见第2.2节:

2.2附件处置类型

车身部件可以指定为“附件”,以表明它们是 独立于邮件消息的主体,并且 显示不应是自动的,但取决于进一步的操作 用户的操作。MUA可能会向用户呈现 带有附件图标表示的位图终端,或, 在字符终端上,带有附件列表,其中 用户可以选择查看或存储

这样设置:

w.Header().Set("Content-Disposition", "attachment; filename=Wiki.png")
另外,在设置响应编写器的标题时,请从您做出的响应中复制字段,而不是从传入的请求中复制字段:

w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
还请注意,标题更像是浏览器的“建议”。这是一件您建议响应是要保存的文件的事情,但是从服务器端,您不能强制浏览器将响应真正保存到文件而不显示它


请参阅相关问题:

设置
附件
而不是
表单数据
内容处置类型。我尝试设置“附件”,但不显示浏览器中的对话框。您还可以从错误的“源”设置内容类型和长度。请看下面我的答案。不适合我,我使用chrome下载。在IE中,默认情况是允许目录保存下载。我理解这取决于浏览器“不适合我”——请解释这意味着什么。您看到了什么以及希望看到什么?我的期望是,单击“下载”按钮后,打开对话框选择一个文件夹来保存文件。但我知道,除了代码实现之外,您还需要设置才能打开浏览器对话框。非常感谢。