英文:
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
的输出中看到我的文件。但是,如果我只尝试获取文件内容,就会失败
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
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论