2
我有一個本地golang服務器,其端點偵聽POST請求,解碼請求的正文並保留它。這工作時,我手動捲曲端點就像在POST請求中將圖像附加到golang服務器
curl -X POST localhost:8080/newimage --data-binary "PATH"
但是,我無法成功上傳在通過GUI我工作的一個POST請求的文件。我正在使用https://github.com/okonet/react-dropzone刪除File並將其附加到FormData對象,但golang服務器似乎沒有收到填充的正文。
這是我如何創建AJAX查詢:
formData = new FormData();
formData.append("image", file)
$.ajax({
url: "http://localhost:8080/items/81d648b0-25f9-434e-9129-fe52575865dd/newimage",
type: "POST",
data: formData,
processData: false
}).done(function(res) {
console.log(res);
});
和後端服務器:
func (h *ItemHandler) PostImage(resp http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
itemID := vars["id"]
assetID := newAssetID()
// verify image
img, _, err := image.Decode(req.Body)
if err != nil {
log.Printf("could not decode body into an image")
resp.Header().Add("Access-Control-Allow-Origin", "*")
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte("could not decode body image"))
return
}
將不勝感激的任何建議。
也許問題是關係到'被設置爲'應用內容Type'頭/ x-www-form-urlencoded「。嘗試將其更改爲'application/octet-stream'。 – hindmost
Go從來沒有這樣做過,但是你應該解碼請求數據的'image'字段嗎?身體可能不包含有效的圖像...更像'image = YourImageEncodingData' – Elwinar
您只檢查'err!= nil',但_what is_錯誤? 'error'不僅僅是一個'bool'類型(是'nil'或者非'nil')... – icza