1.beego官網(wǎng) 2.找到SaveToFile方法 //SaveToFile saves uploaded file to new path. it only operates the first one of mutil-upload form file field.func (c *Controller) SaveToFile(fromfile, tofile string) error {file, _, err := c.Ctx.Request.FormFile(fromfile) if err != nil { return err } defer file.Close() f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } defer f.Close() io.Copy(f, file) return nil } 3.查看beego文檔,在請求參數(shù)中,有上傳文件 (1.)form 表單中,新增屬性 enctype=”multipart/form-data” ,獲取請求參數(shù) c.Input().Get(“id”) (2.)beego提供了兩個方法來處理文件上傳: GetFile(key string) (multipart.File, *multipart.FileHeader, error) //該方法主要用于用戶讀取表單中的文件名 the_file,然后返回相應(yīng)的信息,用戶根據(jù)這些變量來處理文件上傳:過濾、保存文件等 SaveToFile(fromfile, tofile string) error //該方法是在 GetFile 的基礎(chǔ)上實(shí)現(xiàn)了快速保存的功能,fromfile 是提交時(shí)候的 html 表單中的 name (3.) 代碼示例: func (c *FormController) Post() { f, h, err := c.GetFile('uploadname') if err != nil { log.Fatal('getfile err ', err) } defer f.Close() c.SaveToFile('uploadname', 'static/upload/' + h.Filename) // 保存位置在 static/upload, 沒有文件夾要先創(chuàng)建 } (4.) 文件路徑名拼接 path.Join(“path”,fileName) //該函數(shù)會根據(jù)不同的操作系統(tǒng),使用不同的路徑分隔符 (5.)從URL中獲取參數(shù) reqURL := c.ctx.Request.RequestURI //為處理中文 可用 url.QueryUnescape(reqURL) id := strings.LastIndex(reqURL,”/”) tid := requrl[i+1:] 4.使用golang原生的上傳: //SaveToFile saves uploaded file to new path. it only operates the first one of mutil-upload form file field.func (c *Controller) SaveToFile(fromfile, tofile string) error {file, _, err := c.Ctx.Request.FormFile(fromfile) if err != nil { return err } defer file.Close() f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } defer f.Close() io.Copy(f, file) return nil } |
|