1 回答

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
在您的示例中,您試圖讀取 r.Body 就好像它是從請(qǐng)求的 PDF 部分中剝離出來的一樣,但事實(shí)并非如此。您需要分別處理 PDF 和 JSON 這兩個(gè)部分。使用http.(*Request).MultipartReader()。
r.MultipartReader() 將返回mime/multipart.Reader對(duì)象,因此您可以使用r.NextPart()函數(shù)迭代各個(gè)部分并分別處理每個(gè)部分。
所以你的處理函數(shù)應(yīng)該是這樣的:
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)
}
- 1 回答
- 0 關(guān)注
- 383 瀏覽
添加回答
舉報(bào)