将图像从HTML表单传递到Go语言中。

huangapple go评论76阅读模式
英文:

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.

&lt;form action=&quot;/image&quot; method=&quot;post&quot;
enctype=&quot;multipart/form-data&quot;&gt;
&lt;label for=&quot;file&quot;&gt;Filename:&lt;/label&gt;
&lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot;&gt;&lt;br&gt;
&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/form&gt;

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(&quot;file&quot;)

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(&quot;file&quot;)
	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
}

huangapple
  • 本文由 发表于 2014年8月10日 13:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/25225723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定