通过HTTP接收大文件

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

Receive big file via http

问题

我正在为你翻译以下内容:

我试图通过HTTP接收一个大约25MB的文件。我通过PHP和cURL将文件发送给"golang",然后尝试从"golang"接收它。
以下是代码:

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    buf, _ := ioutil.ReadAll(r.Body)
    fmt.Println(string(buf[:]))
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":12100", nil)
}

在这种情况下,我可以在ioutil.ReadAll的输出中看到我的文件。但是,如果我只尝试获取文件内容,就会失败 通过HTTP接收大文件

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(0)
    fmt.Println(r.FormValue("f"))
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":12100", nil)
}

然而,如果文件很小(约900KB),一切都正常。通过HTTP发送大文件的正确方法是什么?

英文:

I've trying to receive big (~25Mb) file via http. From "client" i've send this file via PHP and cUrl and trying to receive it from golang.
Here is code:

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    buf, _ := ioutil.ReadAll(r.Body)
    fmt.Println(string(buf[:]))
}
    
func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":12100", nil)
}

In this case i can see my file in ioutil.ReadAll output. But if i trying to get only file contents, it is failed 通过HTTP接收大文件

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(0)
    fmt.Println(r.FormValue("f"))
}


func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":12100", nil)
}

However file is small (~900Kb) everything is ok. What is right way to send big files via http?

答案1

得分: 3

Go将开始将大文件写入磁盘,以防止它们堵塞内存。然后,您可以使用FormFile获取磁盘上文件的句柄。完成后,应关闭句柄并使用r.MultipartForm.RemoveAll()删除临时文件。

完整代码如下:

func handler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(0)
    defer r.MultipartForm.RemoveAll()
    fi, info, err := r.FormFile("f")
    defer fi.Close()
    fmt.Printf("接收到文件:%v", info.Filename)
    // 对文件进行操作
}
英文:

Go will start writing large files to disk, so that they don't clog up memory.
You can then use FormFile to get the a handle to the file on disk. When you are done you should close the handle and delete the temporary file with r.MultipartForm.RemoveAll().

All together:

func handler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(0)
	defer r.MultipartForm.RemoveAll()
	fi, info, err := r.FormFile("f")
	defer fi.Close()
	fmt.Printf("Recieved %v",info.Filename)
	//Do whatever with it
}

huangapple
  • 本文由 发表于 2016年3月14日 15:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/35981958.html
匿名

发表评论

匿名网友

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

确定