不能发布多个文件

我知道如何上传单个文件,但现在我正尝试在同一个 Go 函数中上传多个文件。


这是我的代码:


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)

}


但我收到此错误:


cannot use file (type *multipart.FileHeader) as type []byte in argument to ioutil.WriteFile

我试过file像这样读入字节:


b, err := ioutil.ReadFile(file) 

    if err != nil {

        fmt.Print(err)

    }

并保存b而不是file.


但后来我得到另一个错误


can not read *multipart.Fileheader as string 

我怎样才能解决这个问题?


精慕HU
浏览 108回答 2
2回答

冉冉说

这里是记录的完整解决方案:// PhotoCreatePOST saves multiple photo uploadsfunc PhotoCreatePOST(w http.ResponseWriter, r *http.Request) {    err := r.ParseMultipartForm(100000)    if err != nil {        fmt.Println("error parsing multiplepart form", err)        return    }    files := r.MultipartForm.File["files"]    for i, _ := range files { //Iterate over multiple uploaded files        file, err := files[i].Open()        defer file.Close()        if err != nil {            fmt.Println("error opening file ", err)            return        }        ext := path.Ext(files[i].Filename)        //TODO: Verify extension is valid        filename := GetRandomString(10) + ext        //create destination file making sure the path is writeable.        dst, err := os.Create("media/photos/" + filename)        defer dst.Close()        if err != nil {            fmt.Println("error creating destination ", err)            return        }        //copy the uploaded file to the destination file        if _, err := io.Copy(dst, file); err != nil {            fmt.Println("error copying file", err)            return        }        fmt.Println("Image upload success: ", files[i].Filename)    }    fmt.Println("all are uploaded")    PhotoCreateGET(w, r)    return }//Generate random filename (never trust user input!)var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789")// GetString returns a random stringfunc GetRandomString(n int) string {    rand.Seed(time.Now().UnixNano())    b := make([]rune, n)    for i := range b {        b[i] = letterRunes[rand.Intn(len(letterRunes))]    }    return string(b)}以及上传表格:<form method="post" action="/create/photo" enctype="multipart/form-data">        <input type="file"  name="files"  multiple>        <input type="hidden" name="token" value="{{.token}}">        <button title="submit" type="submit" >Save </button></form>瞧。希望它可以为其他人节省一些时间。

慕码人8056858

这大致就是您的操作方式。fileHeaders := r.MultipartForm.File["files"]var fileNames []stringfor _, fileHeader := range fileHeaders {&nbsp; &nbsp; file, err := fileHeader.Open()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; // Generate the destination filename randomly. Using even the passed&nbsp; &nbsp; // extension is a security vulnerability unless you have a whitelist.&nbsp; &nbsp; dest, err := ioutil.TempFile("/media/photos", "")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; defer dest.Close()&nbsp; &nbsp; if _, err := io.Copy(dest, file); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; fileNames = append(fileNames, dest.Name())}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go