亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Go 從一個 HTTP 請求中解析文件和 JSON 數據?

如何使用 Go 從一個 HTTP 請求中解析文件和 JSON 數據?

Go
森林海 2021-09-21 22:45:33
我一直在試圖弄清楚如何從 Angularjs 前端的一個 http 請求表單中解析 PDF 文檔和 JSON 數據。請求有效載荷是HTTP 請求內容配置:表單數據;名稱=“文件”;filename="Parent Handbook.pdf" 內容類型:application/pdf內容配置:表單數據;名稱=“文檔”{"title":"test","cat":"test cat","date":20142323}“file”是pdf,“doc”是我要解析的json數據。我的處理程序可以很好地解析和保存文件,但無法從 Json 中獲取任何內容。有任何想法嗎?func (s *Server) PostFileHandler(w http.ResponseWriter, r *http.Request) {    const _24K = (1 << 20) * 24    err := r.ParseMultipartForm(_24K)    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }    doc := Doc{}    jsonDecoder := json.NewDecoder(r.Body)    fmt.Println(r.Body)    err = jsonDecoder.Decode(&doc)    if err != nil {        fmt.Println(err.Error())    }    fmt.Println(doc.Title, doc.Url, doc.Cat, doc.Date)    doc.Id = len(docs) + 1    err = s.db.Insert(&doc)    checkErr(err, "Insert failed")    // files := m.File["myFile"]    for _, fheaders := range r.MultipartForm.File {        for _, hdr := range fheaders {            var infile multipart.File            infile, err = hdr.Open()            // defer infile.Close()            if err != nil {                http.Error(w, err.Error(), http.StatusInternalServerError)                return            }            doc.Url = hdr.Filename            fmt.Println(hdr.Filename)            var outfile *os.File            outfile, err = os.Create("./docs/" + hdr.Filename)            // defer outfile.Close()            if err != nil {                http.Error(w, err.Error(), http.StatusInternalServerError)                return            }            _, err = io.Copy(outfile, infile)            if err != nil {                http.Error(w, err.Error(), http.StatusInternalServerError)                return            }        }    }    s.Ren.JSON(w, http.StatusOK, &doc)    // http.Error(w, "hit file server", http.StatusOK)}
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

在您的示例中,您試圖讀取 r.Body 就好像它是從請求的 PDF 部分中剝離出來的一樣,但事實并非如此。您需要分別處理 PDF 和 JSON 這兩個部分。使用http.(*Request).MultipartReader()。


r.MultipartReader() 將返回mime/multipart.Reader對象,因此您可以使用r.NextPart()函數迭代各個部分并分別處理每個部分。


所以你的處理函數應該是這樣的:


func (s *Server) PostFileHandler(w http.ResponseWriter, r *http.Request) {

    mr, err := r.MultipartReader()

    if err != nil {

        http.Error(w, err.Error(), http.StatusInternalServerError)

        return

    }


    doc := Doc{}

    for {

        part, err := mr.NextPart()


        // This is OK, no more parts

        if err == io.EOF {

            break

        }


        // Some error

        if err != nil {

            http.Error(w, err.Error(), http.StatusInternalServerError)

            return

        }


        // PDF 'file' part

        if part.FormName() == "file" {

            doc.Url = part.FileName()

            fmt.Println("URL:", part.FileName())

            outfile, err := os.Create("./docs/" + part.FileName())

            if err != nil {

                http.Error(w, err.Error(), http.StatusInternalServerError)

                return

            }

            defer outfile.Close()


            _, err = io.Copy(outfile, part)

            if err != nil {

                http.Error(w, err.Error(), http.StatusInternalServerError)

                return

            }

        }


        // JSON 'doc' part

        if part.FormName() == "doc" {

            jsonDecoder := json.NewDecoder(part)

            err = jsonDecoder.Decode(&doc)

            if err != nil {

                http.Error(w, err.Error(), http.StatusInternalServerError)

                return

            }

            fmt.Println(doc.Title, doc.Url, doc.Cat, doc.Date)

        }

    }


    doc.Id = len(docs) + 1

    err = s.db.Insert(&doc)

    checkErr(err, "Insert failed")


    s.Ren.JSON(w, http.StatusOK, &doc)

}


查看完整回答
反對 回復 2021-09-21
  • 1 回答
  • 0 關注
  • 385 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號