helloworld/index.go:
package main
import (
"fmt"
"io"
"net/http"
"os"
)
//写入响应.读取请求
func uploadFile(w http.ResponseWriter,r *http.Request){
err:=r.ParseMultipartForm(10<<20)
//10<<20代表二进制10左移动20位1010000000000000000000,转换为十进制就是 10485760字节。转换成mb的话,是10mb
if err!=nil{//错误就输出错误信息
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file,handler,err:=r.FormFile("file")//文件句柄 文件信息 可能发生的错误
if err!=nil{//错误就输出错误信息
http.Error(w,"error file",http.StatusBadRequest)
return
}
defer file.Close()
dst, err := os.Create("./upload/" + handler.Filename)//保存到当前目录下的upload目录下.handler.Filename 表示从 HTTP 请求中获取的上传文件的原始文件名。
if err != nil {//错误就输出错误信息
http.Error(w, "创建文件错误", http.StatusInternalServerError)
return
}
defer dst.Close()
_,err=io.Copy(dst,file)//把file保存到dst变量中
if err != nil {//错误就输出错误信息
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "File uploaded successfully: %s", handler.Filename)//输出成功信息
}
func main() {
// 创建一个文件服务器,用于提供静态文件
fs := http.FileServer(http.Dir("static"))
// 将文件服务器与根路径 "/" 关联起来
http.Handle("/", fs)
http.HandleFunc("/upload",uploadFile)
http.ListenAndServe(":8080",nil)
}
static/index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
文件上传:
<input type="file" name="file" id="file">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
目录结构:
运行:
http://localhost:8080/
cmd:
F:\gorun\src\HelloWorld>go run index.go
就行了