I know how to upload a single file but now I'm trying to upload multiple files in the same Go function.
Here is my code:
func PhotoCreatePOST(w http.ResponseWriter, r *http.Request) {
var err error
r.ParseMultipartForm(32 << 20) // 32MB is the default used by FormFile
fhs := r.MultipartForm.File["files"]
var fileNames []string
var filename string
var ext string
for _, file := range fhs { //Iterate over multiple uploaded files
if err != nil {
log.Fatal(err)
} else {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
ext = strings.ToLower(path.Ext(file.Filename))
filename = path.Join(random.RandString(10) + ext)
destFolder := "/media/photos"
if _, err := os.Stat(destFolder); os.IsNotExist(err) {
os.Mkdir(destFolder, 0755)
}
//destination Path. The string which is Saving in DB
savePath := destFolder + "/" + filename
err = ioutil.WriteFile(savePath, file, 0777) //<--Here is the problem
if err != nil {
log.Println(err)
io.WriteString(w, err.Error())
return
}
}
}
//Add file url to the slice
fileNames = append(fileNames, filename)
}
But I get this error:
cannot use file (type *multipart.FileHeader) as type []byte in argument to ioutil.WriteFile
I've tried to read the file
into bytes like this:
b, err := ioutil.ReadFile(file)
if err != nil {
fmt.Print(err)
}
And save b
instead of file
.
But then I get another error that
can not read *multipart.Fileheader as string
How can I fix this?