社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
如果使用的是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
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!