如何从Go服务器在浏览器中下载文件 [英] How to download file in browser from Go server

查看:127
本文介绍了如何从Go服务器在浏览器中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码从远程URL获取文件并在浏览器中下载文件:

My code get file from remote url and download file in browser:

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

    ...

    resp, err := client.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(len(body))
    //download the file in browser

}

func main() {
    http.HandleFunc("/", Index)
    err := http.ListenAndServe(":8000", nil)

    if err != nil {
        fmt.Println(err)
    }
}

代码: http://play.golang.org/p/x-EyR2zFjv

获取文件可以,但是如何在浏览器中下载文件?

Get file is ok, but how to downloaded it in browser?

推荐答案

要使浏览器打开下载对话框,请在响应中添加Content-DispositionContent-Type标头:

To make the browser open the download dialog, add a Content-Disposition and Content-Type headers to the response:

w.Header().Set("Content-Disposition", "attachment; filename=WHATEVER_YOU_WANT")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))

在将内容发送到客户端之前执行此操作.您可能还希望将响应的Content-Length标头复制到客户端,以显示适当的进度.

Do this BEFORE sending the content to the client. You might also want to copy the Content-Length header of the response to the client, to show proper progress.

要将响应正文流传输到客户端而不将其完全加载到内存中(对于大文件,这很重要)-只需将正文读取器复制到响应编写器即可:

To stream the response body to the client without fully loading it into memory (for big files this is important) - simply copy the body reader to the response writer:

io.Copy(w, resp.Body)

io.Copy是一个不错的小功能,它具有读取器接口和写入器接口,可从一个接口读取数据并将其写入另一个接口.对于这种东西非常有用!

io.Copy is a nice little function that take a reader interface and writer interface, reads data from one and writes it to the other. Very useful for this kind of stuff!

我已修改您的代码以执行此操作: http://play.golang.org/p/v9IAu2Xu3_

I've modified your code to do this: http://play.golang.org/p/v9IAu2Xu3_

这篇关于如何从Go服务器在浏览器中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆