golang上传文件错误:运行时错误,索引超出范围。

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

golang upload file err runtime error index out of range

问题

我已经整理了一个使用golang编写的函数,该函数接收一个上传的文件并将其保存到文件夹中。在os.Create()之前,我遇到了以下错误:

http: panic serving [::1]:64373: runtime error: index out of range

我的golang函数如下:

func webUploadHandler(w http.ResponseWriter, r *http.Request) {
 
 file, header, err := r.FormFile("file") // FormFile函数接收POST输入的文件id

 if err != nil {
 	fmt.Fprintln(w, err)
 	return
 }
 defer file.Close()

 // 错误出现在这里

 messageId := r.URL.Query()["id"][0]
 out, err := os.Create("./upload/" + messageId + ".mp3")
 
 if err != nil {
 	fmt.Fprintf(w, "无法创建写入文件,请检查写入权限")
 	return
 }
 defer out.Close()

 // 将POST内容写入文件
 _, err = io.Copy(out, file)
 if err != nil {
 	fmt.Fprintln(w, err)
 }

 fmt.Fprintf(w, "文件上传成功:")
 fmt.Fprintf(w, header.Filename)

}

有什么想法吗?非常感谢。

英文:

I've put together a golang func that takes an uploaded file and saves it to folder.
Just before os.Create() I am getting the following error :

http: panic serving [::1]:64373: runtime error: index out of range

My golang function is:

func webUploadHandler(w http.ResponseWriter, r *http.Request) {
 
 file, header, err := r.FormFile("file") // the FormFile function takes in the POST input id file

 if err != nil {
 	fmt.Fprintln(w, err)
 	return
 }
 defer file.Close()

 // My error comes here

 messageId := r.URL.Query()["id"][0]
 out, err := os.Create("./upload/" + messageId + ".mp3")
 
 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)

}

any ideas? much appreciate

答案1

得分: 4

你应该至少检查 r.URL.Query()["id"] 是否实际上有一个元素。

如果 len(r.URL.Query()["id"]),你可以考虑不访问索引0。

更简单的方法是,Ainar-G评论中建议使用Get()方法

Get方法获取与给定键关联的第一个值。
如果与该键关联的值为空,则Get方法返回空字符串
要访问多个值,请直接使用映射。

英文:

You should at least check if r.URL.Query()["id"] has actually one element.

If len(r.URL.Query()["id"]), you could consider not accessing the index 0.

Easier, Ainar-G suggests in the comments to use the Get() method

> Get gets the first value associated with the given key.
If there are no values associated with the key, Get returns the empty string.
To access multiple values, use the map directly.

huangapple
  • 本文由 发表于 2014年9月12日 16:40:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/25804092.html
匿名

发表评论

匿名网友

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

确定