您的位置:首页技术文章

Golang实现http文件上传小功能的案例

【字号: 日期:2023-10-16 16:32:58浏览:44作者:馨心
看代码吧~

package mainimport ('fmt''io''net/http''os')func main() {http.HandleFunc('/', index)http.HandleFunc('/upload', upload)http.ListenAndServe(':1789', nil)}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)if err != nil {fmt.Println(err)return}defer f.Close()io.Copy(f, file)fmt.Fprintln(w, 'upload ok!')}func index(w http.ResponseWriter, r *http.Request) {w.Write([]byte(tpl))}const tpl = `<html><head><title>上传文件</title></head><body><form enctype='multipart/form-data' action='/upload' method='post'> <input type='file' name='uploadfile' /> <input type='hidden' name='token' value='{...{.}...}'/> <input type='submit' value='upload' /></form></body></html>`

补充:Golang 调用http 文件上传接口 进行上传文件

远程服务器有一个文件上传接口,文件用于保存到服务器本地,用go如何调用此接口将文件上传至服务器?

首先,文件上传请求方 与 接收方 要协调工作(解析等工作)

接收方:

func UploadFileToLocal(c echo.Context) error { r := c.Request() //无论用的什么路由,原理是要从request获取数据 t := echotools.NewEchoTools(c) reader, err := r.MultipartReader() //request 获得文件 reader if err != nil { return t.BadRequest(err.Error()) } if reader == nil { return t.BadRequest(`未接受到文件`) } //遍历操作 获得的 for { part, err := reader.NextPart() if err == io.EOF { break } fmt.Printf('FileName=[%s],FormName[%s]n',part.FileName(),part.FormName()) if part.FileName() == '' { data, _ := ioutil.ReadAll(part) fmt.Printf('FormData=[%s]n', string(data)) continue } else { //创建一个空文件 dst, er:= os.Create('static/uploadfiles/' + part.FileName()) if er != nil { return t.BadRequest(err.Error()) } defer dst.Close() //将获取到的文件复制 给 创建的文件 _,err := io.Copy(dst, part) if err != nil { return t.BadRequest(err.Error()) } } } return t.OK(`OK`)}请求方:

func SendFile(c echo.Context) error{ t := echotools.NewEchoTools(c) r := c.Request() file, header, err := r.FormFile('file') // 获得客户端传来的 文件 file if err != nil { return t.BadRequest('上传错误:' + err.Error()) } bodyBuffer := &bytes.Buffer{} bodyWriter := multipart.NewWriter(bodyBuffer) fileWriter, _ := bodyWriter.CreateFormFile('files', header.Filename) io.Copy(fileWriter, file) //将 客户端文件 复制给 用于传输的 fileWriter contentType := bodyWriter.FormDataContentType() //contentType bodyWriter.Close() ip := config.Opts.UploadServerAddr //配置 resp, _ := http.Post('http://'+ip+'/uploadToLocal/'+header.Filename, contentType, bodyBuffer) defer resp.Body.Close() resp_body, _ := ioutil.ReadAll(resp.Body) if resp.Status == `200 OK` { return t.OK(string(resp_body)) }else { return t.BadRequest(string(resp_body)) }}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持优爱好网。如有错误或未考虑完全的地方,望不吝赐教。

标签: Golang
相关文章: