2016-03-06 158 views
0

在我的使用案例中,我試圖上傳一個文件到golang的服務器。我有以下的HTML代碼,golang文件上傳失敗

<div class="form-input upload-file" enctype="multipart/form-data" > 
    <input type="file"name="file" id="file" /> 
    <input type="hidden"name="token" value="{{.}}" /> 
    <a href="/uploadfile/" data-toggle="tooltip" title="upload"> 
     <input type="button upload-video" class="btn btn-primary btn-filled btn-xs" value="upload" /> 
    </a> 
</div> 

而在服務器端,

func uploadHandler(w http.ResponseWriter, r *http.Request) { 
    // the FormFile function takes in the POST input id file 
    file, header, err := r.FormFile("file") 
    if err != nil { 
     fmt.Fprintln(w, err) 
     return 
    } 
    defer file.Close() 

    out, err := os.Create("/tmp/uploadedfile") 
    if err != nil { 
     fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege") 
     return 
    } 
    defer out.Close() 

    // write the content from POST to the file 
    _, err = io.Copy(out, file) 
    if err != nil { 
     fmt.Fprintln(w, err) 
    } 

    fmt.Fprintf(w, "File uploaded successfully : ") 
    fmt.Fprintf(w, header.Filename) 
} 

當我嘗試上傳的文件,我得到在服務器端request Content-Type isn't multipart/form-data錯誤。

任何人都可以幫助我嗎?

回答

1

說實話,我不知道你怎麼會得到錯誤,因爲你的HTML不是形式。但我認爲你得到的錯誤,因爲默認形式發送爲GET請求,而multipart/form-data應通過POST發送。這是應該工作的最小形式的例子。

<form action="/uploadfile/" enctype="multipart/form-data" method="post"> 
    <input type="file" name="file" id="file" /> 
    <input type="hidden"name="token" value="{{.}}" /> 
    <input type="submit" value="upload" /> 
</form> 
+0

謝謝。我試圖在另一種形式中使用這個。所以我嘗試了這種方式。有沒有任何工作可以在另一個表單中使用它?這將是非常有幫助 – Dany

+0

@DineshAppavoo窗體內部窗體? –

+0

看起來不可能[nest-forms](http://stackoverflow.com/questions/379610/can-you-nest-html-forms)。我試過了,原始形式正在崩潰。有沒有解決方法? – Dany

1

問題是您必須包含包含內容類型的標頭。

req.Header.Add("Content-Type", writer.FormDataContentType()) 

這包含在mime/multipart包中。

對於一個工作示例,請檢查this博客文章。

+0

他並非試圖從Go應用發送表單。他無法在Go應用中獲取HTML表單數據。 –

+0

是的,這就是他收到上述錯誤的原因。 –

+0

他的Go代碼完全適用於正確的HTML表單。而你的鏈接是關於從Go發送數據到遠程服務。 –