golang吧 关注:6,266贴子:14,399
  • 13回复贴,共1

请教:html5批量文件上传,服务端go怎么接收多个文件?

只看楼主收藏回复

下面是go代码,这个代码只能接收一个文件,如果要接收多个文件,请问怎么办?
func upload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
fmt.Printf("---- %v\n",handler.Filename)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintln(w, "upload ok!")
}
下面是上传功能html5代码,input使用了multiple属性,支持多文件上传
const tpl = `<html>
<head>
<title>WEB文件管理</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" multiple name="uploadfile"/>
<input type="submit" value="上传" />
</form>
</body>
</html>`
-- 可视 -- 37 19,1 底端


IP属地:广西1楼2018-06-24 16:36回复
    6月24日晚上已搞定


    IP属地:广西2楼2018-07-04 11:47
    回复(4)
      楼主在吗? 我最近也在学习这个,不知道怎么批量上传, 你是怎么做的呢


      IP属地:山西3楼2018-08-09 17:23
      回复(6)
        //多文件批量上传
        func upload(w http.ResponseWriter, r *http.Request) {
        r.ParseMultipartForm(64 << 20) //64MB内存buffer
        var uplFail, upSucc int
        var rename string
        for _, fileHeader := range r.MultipartForm.File["uploadfile"] {
        srcFile, err := fileHeader.Open()
        if err != nil {
        log.Println(err)
        return
        }
        fpath := filepath.Join(curDir, fileHeader.Filename)
        originPath := fpath
        for {
        _, err := os.Stat(fpath)
        if err == nil {
        //如果文件存在,则重命名上传文件(.扩展名前加"_New")
        suffix := filepath.Ext(fpath)
        withoutSuf := strings.TrimSuffix(fpath, suffix)
        fpath = withoutSuf + "_New" + suffix
        } else {
        break
        }
        }
        if originPath != fpath {
        rename = rename + fmt.Sprintf("%-s&nbsp&nbsp<b>上传后被重命名为:</b>&nbsp&nbsp%-s </br>", originPath, fpath)
        }
        dstFile, err := os.Create(fpath) //创建上传文件
        if err != nil {
        log.Println(err)
        srcFile.Close()
        return
        }
        _, err = io.Copy(dstFile, srcFile)
        if err != nil {
        uplFail++
        } else {
        log.Printf("%s upload %q success\n", r.RemoteAddr[:strings.LastIndex(r.RemoteAddr, ":")], filepath.Join(root, dstFile.Name()))
        upSucc++
        }
        srcFile.Close() //这里是循环,避免用defer *.Close()
        dstFile.Close()
        }
        fmt.Fprintf(w, "<h1>上传失败:%d, 成功:%d</h1> <p>%s</p> <script language='javascript' type='text/javascript'> setTimeout(\"javascript:location.href='%s'\", %d000); </script>", uplFail, upSucc, rename, curDir, 1+len(strings.Split(rename, "</br>")))
        }


        IP属地:广西5楼2018-09-21 08:47
        回复