golang - 如何从golang服务器下载浏览器中的文件? [英] golang - how to download file in browser from golang server?

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

问题描述

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

  func索引(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))
//在浏览器中下载文件


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

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

code:http://play.golang.org/p/x-EyR2zFjv



获取文件是好的,但如何在浏览器中下载它?



Th为了让浏览器打开下载对话框,添加一个 Content-Disposition c $ c>和 Content-Type 标题到响应:

  w.Header()。Set(Content-Disposition,attachment;文件名= WHATEVER_YOU_WANT)
w.Header()。Set(Content-Type,r.Header.Get(Content-Type))

在将内容发送到客户端之前执行此操作。您可能还需要复制 Content-Length 的标题对客户端的响应,以显示正确的进度。



将响应主体流式传输到客户端而不将其完全加载到内存中(对于大文件这很重要)将身体阅读器复制到回复作者:

  io.Copy(w,resp.Body)

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



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


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)
    }
}

code: http://play.golang.org/p/x-EyR2zFjv

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

Thanks.

解决方案

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"))

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 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!

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

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

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