英文:
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 << 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)}
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论