How to download file in browser from Go server

前端 未结 3 1776
走了就别回头了
走了就别回头了 2020-12-12 18:24

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/         


        
3条回答
  •  被撕碎了的回忆
    2020-12-12 19:04

    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_

提交回复
热议问题