如何在Go中从multipart. part中获取multipart. file而不保存到磁盘?

vmjh9lq9  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(73)

在我的go API中,我有一个函数,它以前工作得很好,可以像这样从r.Body中提取multipart.File

file, handler, err := r.FormFile("file")

字符串
我使用multipart.File上传到使用minio客户机的s3 API,如下所示

err = uploadToMinio(rs, file, fileSize, fileName, guid.String(), userId)


现在我已经添加了额外的表单数据,用户r.body似乎无法再这样做了。我得到了“错误获取表单文件”,如下面的代码所示。
this question之后,我实现了一个MultipartReader来从multipart.Part获取表单数据。
部分没有multipart.File,所以我需要得到这一点,没有写的一部分到磁盘和阅读它再次如果可能的话。
这是我的代码

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
        }

u4dcyp6a

u4dcyp6a1#

您已经在流式传输表单的各个部分,现在不能调用FormFile,您必须自己读取文件。使用part.Read读取文件的字节,或复制它,等等。注意part实现了io.Reader,因此您可以像阅读文件一样读取它。

相关问题