英文:
go) how to i make download service?
问题
我可以帮你翻译代码部分,以下是翻译好的内容:
我创建了一个上传服务器
但是我无法创建下载服务器
package main
import (
"fmt"
"io"
"os"
"github.com/gin-gonic/gin"
)
func uploadHandler(c *gin.Context) {
uid := c.Request.FormValue("uid")
file, header, err := c.Request.FormFile("uploadFile")
filename := header.Filename
fmt.Println(filename)
err = os.Mkdir("./upload/"+uid, 777)
out, err := os.Create("./upload/" + uid + "/" + filename)
_, err = io.Copy(out, file)
}
func downloadHandler(c *gin.Context) {
uid := c.Request.FormValue("uid")
downloadfilename := c.Request.FormValue("downloadfilename")
filepath := "./upload/" + uid + "/" + downloadfilename
c.File(filepath)
}
func main() {
r := gin.Default()
r.POST("/goupload", uploadHandler)
r.POST("/godownload", downloadHandler)
// 监听并在 0.0.0.0:8080 上提供服务
r.Run()
}
所以,你可以使用 POST 请求发送 uid 和 downloadfilename 来创建下载服务器。
英文:
i make upload server
but i can't make download server
package main
import (
"fmt"
"io"
"os"
"github.com/gin-gonic/gin"
)
func uploadHandler(c *gin.Context) {
uid := c.Request.FormValue("uid")
file, header, err := c.Request.FormFile("uploadFile")
filename := header.Filename
fmt.Println(filename)
err = os.Mkdir("./upload/"+uid, 777)
out, err := os.Create("./upload/" + uid + "/" + filename)
_, err = io.Copy(out, file)
}
func main() {
r := gin.Default()
r.POST("/goupload", uploadHandler)
r.POST("/godownload", downloadHandler)
// listen and server on 0.0.0.0:8080
r.Run()
}
so, how to i make download server?
i will use post uid & downloadfilename.
答案1
得分: 3
你可以编写一个新的处理程序,并使用http包中的ServeContent或ServeFile方法。
f, err := os.Open(yourFile)
if err != nil {
return err
}
defer f.Close()
fileInfo, err := f.Stat()
if err != nil {
return err
}
http.ServeContent(w, r, fileInfo.Name(), fileInfo.ModTime(), f)
如果要强制浏览器打开下载对话框,可以添加Content-Disposition
和Content-Type
头,并将文件内容写入响应体:
f, err := os.Open(yourFile)
if err != nil {
return err
}
defer f.Close()
w.Header().Set("Content-Disposition", "attachment; filename=YourFile")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
io.Copy(w, f)
英文:
You can write an new handler and use ServeContent or ServeFile from http package.
f, err := os.Open(yourFile)
if err != nil {
return err
}
defer f.Close()
fileInfo, err := f.Stat()
if err != nil {
return err
}
http.ServeContent(w, r, fileInfo.Name(), fileInfo.ModTime(), f)
To force the browser open the download dialog, add a Content-Disposition
and Content-Type
headers and write to file content to the body:
f, err := os.Open(yourFile)
if err != nil {
return err
}
defer f.Close()
w.Header().Set("Content-Disposition", "attachment; filename=YourFile")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
io.Copy(w, f)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论