我正在使用golang net/http包构建一个webserver.And,现在我必须处理大文件上传,这意味着服务器可能会收到请求,Expect: 100 Continue.I将不会向客户发送响应,直到每次完成一个请求并返回时,所有数据都是received.However之后,golang默认会发送一个响应,我如何实现?
发布于 2018-04-09 08:31:07
使用request.ParseMultipartForm,
ParseMultipartForm将请求体解析为多部分/表单数据。对整个请求正文进行解析,其文件部分的maxMemory字节最多存储在内存中,其余部分存储在临时文件中的磁盘上。如果有必要,ParseMultipartForm会调用ParseForm。在对ParseMultipartForm进行一次调用之后,后续调用没有任何效果。
So yo just can do:
import(
"ioutil"
"net/http"
)
//check all posible errors, I´m assuming you just have one file per key
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(1000000) //1 MB in memory, the rest in disk
datas := r.MultipartForm
for k, headers := range datas.File {
auxiliar, _ := headers[0].Open() //first check len(headers) is correct
fileName:=headers[0].Filename
file, _ := ioutil.ReadAll(auxiliar)
// do what you need to do with the file
}
}在frontEnd中,您应该有如下所示的javascript:
function handleFile(url,file){
let data=new FormData();
data.append("key",file); //this is the key when ranging over map at backEnd
fetch(url,{method:"PUT",body:data})
}
https://stackoverflow.com/questions/19267336
复制相似问题