Accessing Uploaded Files in Golang

前端 未结 2 406
傲寒
傲寒 2021-02-08 21:20

I\'m having issues with accessing files i upload w/ golang. I\'m really new to the language and have gone through more than a few attempts-- can\'t find any answers to this onli

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 22:18

    If you know they key of the file upload you can make it a bit simpler I think (this is not tested):

    infile, header, err := r.FormFile("file")
    if err != nil {
        http.Error(w, "Error parsing uploaded file: "+err.Error(), http.StatusBadRequest)
        return
    }
    
    // THIS IS VERY INSECURE! DO NOT DO THIS!
    outfile, err := os.Create("./uploaded/" + header.Filename)
    if err != nil {
        http.Error(w, "Error saving file: "+err.Error(), http.StatusBadRequest)
        return
    }
    
    _, err = io.Copy(outfile, infile)
    if err != nil {
        http.Error(w, "Error saving file: "+err.Error(), http.StatusBadRequest)
        return
    }
    
    fmt.Fprintln(w, "Ok")
    

提交回复
热议问题