duanbanzhi4419 2014-09-12 08:40
浏览 85
已采纳

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

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条回答 默认 最新

  • douweida2669 2014-09-12 08:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?