Dan*_*any 5 upload file multipart go
在我的用例中,我尝试将文件上传到 golang 中的服务器。我有以下 html 代码,
<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>
Run Code Online (Sandbox Code Playgroud)
而服务器端,
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)
}
Run Code Online (Sandbox Code Playgroud)
request Content-Type isn't multipart/form-data当我尝试上传文件时,服务器端出现错误。
有人能帮我解决这个问题吗?
说实话,我不知道你怎么会出现错误,因为你的 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>
Run Code Online (Sandbox Code Playgroud)