golang文件上传 - Go语言中文社区

golang文件上传


方法一

如果使用的是beego框架
this.Ctx.Input.RequestBody
通过这个方法,其中文件的内容就包含在其中。
采用post方法
在这里插入图片描述

在这里插入图片描述

方法二

    func uploadHandler(w http.ResponseWriter, r *http.Request) {
    	file, err := os.Create("./newFile.png")
    	if err != nil {
    		panic(err)
    	}
    	_, err = io.Copy(file, r.Body)
    	if err != nil {
    		panic(err)
    	}
    	w.Write([]byte("upload success"))
    }
    
    func main() {
    	http.HandleFunc("/upload", uploadHandler)
    	http.ListenAndServe(":5050", nil)
    }

![在这里插入图片描述](https://img-blog.csdnimg.cn/20190525203358704.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190525203418158.png)

    file, err := os.Open("./qr.png")
    	if err != nil {
    		panic(err)
    	}
    	defer file.Close()
    
    	res, err := http.Post("http://127.0.0.1:5050/upload", "binary/octet-stream", file)
    	if err != nil {
    		panic(err)
    	}
    	defer res.Body.Close()
    	message, _ := ioutil.ReadAll(res.Body)
    	fmt.Printf(string(message))

方法三

package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
)

func uploadHandler2(w http.ResponseWriter, r *http.Request) {
	fmt.Println("------uploadHandler2----")
	switch r.Method {
	//POST takes the uploaded file(s) and saves it to disk.
	case "POST":
		//parse the multipart form in the request
		err := r.ParseMultipartForm(100000)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		//get a ref to the parsed multipart form
		m := r.MultipartForm

		//get the *fileheaders
		files := m.File["uploadfile"]
		for i, _ := range files {
			//for each fileheader, get a handle to the actual file
			file, err := files[i].Open()
			defer file.Close()
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			fmt.Println("-----33----",files[i].Filename)

			datafile := make([]byte, files[i].Size)
			hash := md5.New()
			hash.Write(datafile)
			sum := hash.Sum(nil)
			toString := hex.EncodeToString(sum)
			fmt.Println(toString)

			fmt.Println(path.Ext(files[i].Filename))

			//create destination file making sure the path is writeable.
			dst, err := os.Create("./upload/" + toString+path.Ext(files[i].Filename))
			if err!=nil {
				fmt.Println("err",err)
			}
			defer dst.Close()
			if err != nil {
				fmt.Println("---------------")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			//copy the uploaded file to the destination file
			if _, err := io.Copy(dst, file); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

		}

	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func main() {
	http.HandleFunc("/upload", uploadHandler2)

	//static file handler.
	http.Handle("/staticfile/", http.StripPrefix("/staticfile/", http.FileServer(http.Dir("./staticfile"))))

	//Listen on port 8080
	http.ListenAndServe(":8081", nil)
}

在这里插入图片描述
删除Content-Type

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_30505673/article/details/90551190
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢