Golang服务响应文件

huangapple go评论75阅读模式
英文:

Golang services response file

问题

如何在Go中更高效地从服务返回文件?例如,我接收到一个文件,代码如下:

这是我用来从服务接收文件的示例代码:

func (b *BenefitListHandler) UploadAppend(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(32 << 20)
    file, handler, err := r.FormFile("benefitlistuploadfile")
    if err != nil {
        libhttp.EncodeErrorResponse(w, err, http.StatusInternalServerError)
        return
    }
    defer file.Close()
    f, err := os.OpenFile("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        libhttp.EncodeErrorResponse(w, err, http.StatusInternalServerError)
        return
    }

    defer f.Close()
    io.Copy(f, file)

    go b.readFileAppend("./" + handler.Filename)

    libhttp.EncodeOKResponse(w, true)
}

之后,我对如何从该请求中发送另一个文件(如二进制文件)以提高时间和资源消耗感到困惑。

英文:

How can I return a file from a service more efficiently in Go? For example, I receive a file like this

Here is an example that i use to receive a file from the service:

func (b *BenefitListHandler) UploadAppend(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 &lt;&lt; 20)
	file, handler, err := r.FormFile(&quot;benefitlistuploadfile&quot;)
	if err != nil {
		libhttp.EncodeErrorResponse(w, err, http.StatusInternalServerError)
		return
	}
defer file.Close()
f, err := os.OpenFile(&quot;./&quot;+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
	libhttp.EncodeErrorResponse(w, err, http.StatusInternalServerError)
	return
}

defer f.Close()
io.Copy(f, file)

go b.readFileAppend(&quot;./&quot; + handler.Filename)

libhttp.EncodeOKResponse(w, true)}

After that, I am confused how I can send another file from that request like a binary, to improve the time and consumption.

答案1

得分: 2

在查看了问题的信息后,我得到了解决方案。

要指定一个作为文件的浏览器,我将以下标头添加到响应中:

w.Header().Set("Content-Disposition", "attachment; filename=文件名")

然后,我使用ioutil来读取文件:

files, err := ioutil.ReadFile(result)

最后,我使用http.ResponseWriter将文件的[]byte写入响应中:

w.Write(files)
英文:

after look information about the question i get that solution

to specify a browser that is a file i put that header to the response:

> w.Header().Set("Content-Disposition", "attachment;
> filename=NameOfFile")

after that i read the file with ioutil:

> files, err := ioutil.ReadFile(result)

and at the end i use the http.ResponseWriter to write the []byte of the file to the response

> w.Write(files)

huangapple
  • 本文由 发表于 2017年9月12日 08:05:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/46165999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定