File upload golang上载文件错误运行时错误索引超出范围
我已经把一个golang func放在一起,它接受一个上传的文件并将其保存到文件夹中。 就在File upload golang上载文件错误运行时错误索引超出范围,file-upload,go,runtime-error,File Upload,Go,Runtime Error,我已经把一个golang func放在一起,它接受一个上传的文件并将其保存到文件夹中。 就在os.Create()之前,我遇到了以下错误: http:panic服务[::1]:64373:运行时错误:索引超出范围 我的golang功能是: func webUploadHandler(w http.ResponseWriter, r *http.Request) { file, header, err := r.FormFile("file") // the FormFile function
os.Create()
之前,我遇到了以下错误:
http:panic服务[::1]:64373:运行时错误:索引超出范围
我的golang功能是:
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)
}
有什么想法吗?非常感谢您至少应该检查
r.URL.Query()[“id”]
实际上是否有一个元素
如果<代码> LeN(R.URL.Quices)([ ID ])< /C>,您可以考虑不访问索引0。
更简单,建议使用 Get获取与给定键关联的第一个值。如果没有与键关联的值,Get将返回空字符串
要访问多个值,请直接使用映射
您至少应该检查
r.URL.Query()[“id”]
是否实际上有一个元素
如果<代码> LeN(R.URL.Quices)([ ID ])< /C>,您可以考虑不访问索引0。
更简单,建议使用 Get获取与给定键关联的第一个值。如果没有与键关联的值,Get将返回空字符串
要访问多个值,请直接使用映射
@bboy解释了索引外错误消息,您需要调整代码以处理该情况。@bboy我已编辑了答案:您也可以使用Get来处理“id”返回值为空字符串的情况。同样的问题。至于缺少“id”,我怀疑您的URL格式不正确,属性无法识别。@bboy这解释了索引外错误消息,您需要调整代码以处理该情况。@bboy我已编辑了答案:您也可以使用Get,并处理“id”返回值为空字符串的情况。同样的问题。至于缺少“id”,我怀疑您的URL格式不正确,属性也无法识别。