在學習golang的過程中,我試圖編寫一個具有多個圖像上傳功能的Web應用程序。Golang處理圖像通過多部分和流到Azure
我正在使用Azure Blob存儲來存儲圖像,但我無法將圖像從多部分請求傳輸到Blob存儲。
這裏是我到目前爲止已經寫的處理程序:
func (imgc *ImageController) UploadInstanceImageHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
reader, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for {
part, partErr := reader.NextPart()
// No more parts to process
if partErr == io.EOF {
break
}
// if part.FileName() is empty, skip this iteration.
if part.FileName() == "" {
continue
}
// Check file type
if part.Header["Content-Type"][0] != "image/jpeg" {
fmt.Printf("\nNot image/jpeg!")
break
}
var read uint64
fileName := uuid.NewV4().String() + ".jpg"
buffer := make([]byte, 100000000)
// Get Size
for {
cBytes, err := part.Read(buffer)
if err == io.EOF {
fmt.Printf("\nLast buffer read!")
break
}
read = read + uint64(cBytes)
}
stream := bytes.NewReader(buffer[0:read])
err = imgc.blobClient.CreateBlockBlobFromReader(imgc.imageContainer, fileName, read, stream, nil)
if err != nil {
fmt.Println(err)
break
}
}
w.WriteHeader(http.StatusOK)
}
在我的研究過程中,我已經通過使用r.FormFile,ParseMultipartForm閱讀,但最終還是決定嘗試學習如何使用MultiPartReader。
我能夠上傳圖像到golang後端,並使用MultiPartReader將文件保存到我的機器。
目前,我可以將文件上傳到Azure,但它們最終被損壞。文件大小看起來很重要,但顯然有些東西不起作用。
我誤解了如何爲CreateBlockBlobFromReader創建一個io.Reader?
任何幫助非常感謝!
嗨馬克感謝回答。我試圖查看是否可以直接將部分內容傳遞給CreateBlockBlobFromReader,但是我從Azure中得到一個錯誤,說該體長度爲0,因此與Content-Length(我以「read」傳入的內容)不匹配。 。你知道這是爲什麼嗎?我會嘗試再次直接傳遞。 –
安德魯見上面彼得的有用答案。 – Mark