从服务器响应Golang / React下载文件

时间:2017-09-19 00:23:36

标签: google-chrome http xmlhttprequest

因此,下载文件工作正常,但在下载整个文件之前,客户端没有浏览器输入。

以下是回复的提取

let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + that.props.jwt)
xhr.setRequestHeader("Content-type", "application/octet-stream")
xhr.responseType = 'arraybuffer'

xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new Blob([this.response], { type:"application/octet-stream" })
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = name + "." + format
    link.click()
  }
}

xhr.send()

以下是响应内容的服务器

var f *os.File
f, err = os.Open(fpath)
if err != nil {
        s.log.Error(fmt.Sprint(err))
        internalError(w, err)
        return
}

modtime := time.Now()

// tell the browser the returned content should be downloaded
w.Header().Add("Content-Disposition", "attachment; filename="+f.Name()+".zip")
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Add("Access-Control-Expose-Headers", "Content-Disposition")
http.ServeContent(w, r, f.Name(), modtime, f)

谢谢,

Ť

0 个答案:

没有答案