英文:
Passing a Image from a html form to Go
问题
我有一个包含以下代码的HTML页面。
<form action="/image" method="post"
enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="提交">
</form>
然后我有一些Go代码来在后端获取文件。
func uploaderHandler(w http.ResponseWriter, r *http.Request) {
userInput := r.FormValue("file")
但是每当我尝试从Go脚本中使用userInput时,它返回空值。我传递变量的方式有问题吗?
编辑:我知道如何上传文本/密码到Golang。我在使用上述代码上传图像时遇到了问题。
编辑2:阅读了Go指南并找到了解决方案。请参见下文。
英文:
I have a html page that has the follow code.
<form action="/image" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
I then have some Go code to get the file on the back end.
func uploaderHandler(w http.ResponseWriter, r *http.Request) {
userInput := r.FormValue("file")
but anytime I try to use userInput from the go script, it returns nothing. Am I passing the variables wrong?
EDIT: I know how to upload things to golang that are text/passwords. I am having trouble uploading images to Go with the code.
EDIT 2: Read the Go guide a found the solution. See below.
答案1
得分: 4
首先,你需要使用req.FormFile
而不是FormValue
,然后你需要手动将图像保存到文件中。
代码示例如下:
func HandleUpload(w http.ResponseWriter, req *http.Request) {
in, header, err := req.FormFile("file")
if err != nil {
//处理错误
}
defer in.Close()
//你可能需要确保header.Filename是唯一的,并使用filepath.Join将其放在其他位置。
out, err := os.OpenFile(header.Filename, os.O_WRONLY, 0644)
if err != nil {
//处理错误
}
defer out.Close()
io.Copy(out, in)
//进行其他操作
}
英文:
First you need to use req.FormFile
not FormValue
, then you will have to manually save the image to a file.
Something like this:
func HandleUpload(w http.ResponseWriter, req *http.Request) {
in, header, err := req.FormFile("file")
if err != nil {
//handle error
}
defer in.Close()
//you probably want to make sure header.Filename is unique and
// use filepath.Join to put it somewhere else.
out, err := os.OpenFile(header.Filename, os.O_WRONLY, 0644)
if err != nil {
//handle error
}
defer out.Close()
io.Copy(out, in)
//do other stuff
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论