在我的go API中,我有一个函数,它以前工作得很好,可以像这样从r.Body
中提取multipart.File
file, handler, err := r.FormFile("file")
我使用multipart.File
通过Minio客户端上传到S3API,如下所示
err = uploadToMinio(rs, file, fileSize, fileName, guid.String(), userId)
现在我已经添加了额外的表单数据,似乎不能再为此使用r.Body.我收到"获取表单文件时出错",如下面的代码所示.
在this question之后,我实现了一个MultipartReader
来从多方获取表单数据.
Part没有multipart.File
,所以如果可能的话,我需要在不将Part写入磁盘并再次读取的情况下达到该值.
以下是我的代码
var err error
start := time.Now()
const maxUploadSize = 500 * 1024 * 1024 // 500 Mb
var requiredByDate FileRequiredDateData
mr, err := r.MultipartReader()
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for {
part, err := mr.NextPart()
// This is OK, no more parts
if err == io.EOF {
break
}
// Some error
if err != nil {
log.Println("multipart reader other error")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println(part.FormName())
if part.FormName() == "data" {
log.Println("multipart reader found multipart form name data")
decoder := json.NewDecoder(part)
err = decoder.Decode(&requiredByDate)
if err != nil {
log.Println("error in decoding request body data")
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if part.FormName() == "file" {
file, handler, err := r.FormFile("file") <-- error getting form file here
if err != nil {
log.Println("error getting form file")
log.Println(err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusInternalServerError)
return
}
defer file.Close()
----
err = uploadToMinio(rs, file, fileSize, fileName, guid.String(), userId)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}