如何让客户端在下载文件时打开保存文件对话框

cuo*_*ong 2 http download go web

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

我的服务器端下载代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

如果您希望将响应保存在客户端,请使用"attachment"内容处置类型。rfc2183 的2.2 节对此进行了详细介绍:

2.2 附件处理类型

正文部分可以被指定为“附件”,以指示它们与邮件消息的主体分开,并且它们的显示不应该是自动的,而是取决于用户的一些进一步操作。MUA 可能会向位图终端的用户呈现附件的图标表示,或者在字符终端上向用户呈现附件列表,用户可以从中选择进行查看或存储。

所以这样设置:

w.Header().Set("Content-Disposition", "attachment; filename=Wiki.png")
Run Code Online (Sandbox Code Playgroud)

此外,在设置响应编写器的标头时w,请从您所做的响应中复制字段,而不是从传入请求中复制字段:

w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
Run Code Online (Sandbox Code Playgroud)

另请注意,标头更像是对浏览器的“建议” 。这是您建议响应是要保存的文件的一件事,但从服务器端您不能强制浏览器真正将响应保存到文件而不显示它。

请参阅相关问题:Golang beego output to csv file dumps the data to browser but not dump to file