如何使用go的net / http或类似的替代方案保存多部分/表单数据POST请求中收到的文件?

对于上下文,我正在尝试为程序ShareX创建自定义图像上传器(https://getsharex.com/docs/custom-uploader)。我已经尝试了许多搜索词,但是我找不到这个问题的任何解决方案。


这是我当前的代码(位于文件main.go中):


package main


import (

    "fmt"

    "net/http"

)


func handleUpload(w http.ResponseWriter, r *http.Request) {

    r.ParseMultipartForm(16384)

    f, fi, _ := r.FormFile("file_image")

    _ = f

    fmt.Println(fi.Filename, fi.Size)


}


func main() {

    mux := http.NewServeMux()

    mux.HandleFunc("/upload", handleUpload)

    fmt.Println("Starting listener on port 8085")

    http.ListenAndServe(":8085", mux)

}

我的目标是将从请求中收到的文件(图像)数据保存到本地文件,但是我无法做到这一点,因为写入文件需要类型并且是类型。[]bytefmultipart.File


慕雪6442864
浏览 137回答 1
1回答

富国沪深

这是如何处理表单数据的示例。这里的主要思想是使用io pkg https://golang.org/pkg/io/r.FormFile返回类型的接口。 实现和方法。因此,我们可以从一个文件中复制内容并将其写入空文件。FileFileReaderWriterpackage mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os")func uploadHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; switch r.Method {&nbsp; &nbsp; case "POST":&nbsp; &nbsp; &nbsp; &nbsp; r.ParseMultipartForm(10 << 20) //10 MB&nbsp; &nbsp; &nbsp; &nbsp; file, handler, err := r.FormFile("file_image")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("error retrieving file", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; &nbsp; &nbsp; dst, err := os.Create(handler.Filename)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("error creating file", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer dst.Close()&nbsp; &nbsp; &nbsp; &nbsp; if _, err := io.Copy(dst, file); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(w, "uploaded file")&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; http.HandleFunc("/upload", uploadHandler)&nbsp; &nbsp; http.ListenAndServe(":8085", nil)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go