分享
Go文件上传下载
愚辛 · · 1684 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
Go自带很多包,本例使用io包和net包相应的API简单实现基于http的文件上传下载(仅为demo)
定义文件存储文件
//假设文件上传为本地的服务器,上传的基础路径
const BaseUploadPath = "/var/file"
复制代码main函数中监听http服务
func main() {
http.HandleFunc("/upload", handleUpload)
http.HandleFunc("/download", handleDownload)
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("Server run fail")
}
}
复制代码文件上传处理器
func handleUpload (w http.ResponseWriter, request *http.Request) {
//文件上传只允许POST方法
if request.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("Method not allowed"))
return
}
//从表单中读取文件
file, fileHeader, err := request.FormFile("file")
if err != nil {
_, _ = io.WriteString(w, "Read file error")
return
}
//defer 结束时关闭文件
defer file.Close()
log.Println("filename: " + fileHeader.Filename)
//创建文件
newFile, err := os.Create(BaseUploadPath + "/" + fileHeader.Filename)
if err != nil {
_, _ = io.WriteString(w, "Create file error")
return
}
//defer 结束时关闭文件
defer newFile.Close()
//将文件写到本地
_, err = io.Copy(newFile, file)
if err != nil {
_, _ = io.WriteString(w, "Write file error")
return
}
_,_ = io.WriteString(w, "Upload success")
}
复制代码文件下载处理器
func handleDownload (w http.ResponseWriter, request *http.Request) {
//文件上传只允许GET方法
if request.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("Method not allowed"))
return
}
//文件名
filename := request.FormValue("filename")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
log.Println("filename: " + filename)
//打开文件
file, err := os.Open(BaseUploadPath + "/" + filename)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
//结束后关闭文件
defer file.Close()
//设置响应的header头
w.Header().Add("Content-type", "application/octet-stream")
w.Header().Add("content-disposition", "attachment; filename=\""+filename+"\"")
//将文件写至responseBody
_, err = io.Copy(w, file)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
}
复制代码参考资料:golang.org/pkg/
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1684 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
Go自带很多包,本例使用io包和net包相应的API简单实现基于http的文件上传下载(仅为demo)
定义文件存储文件
//假设文件上传为本地的服务器,上传的基础路径
const BaseUploadPath = "/var/file"
复制代码main函数中监听http服务
func main() {
http.HandleFunc("/upload", handleUpload)
http.HandleFunc("/download", handleDownload)
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("Server run fail")
}
}
复制代码文件上传处理器
func handleUpload (w http.ResponseWriter, request *http.Request) {
//文件上传只允许POST方法
if request.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("Method not allowed"))
return
}
//从表单中读取文件
file, fileHeader, err := request.FormFile("file")
if err != nil {
_, _ = io.WriteString(w, "Read file error")
return
}
//defer 结束时关闭文件
defer file.Close()
log.Println("filename: " + fileHeader.Filename)
//创建文件
newFile, err := os.Create(BaseUploadPath + "/" + fileHeader.Filename)
if err != nil {
_, _ = io.WriteString(w, "Create file error")
return
}
//defer 结束时关闭文件
defer newFile.Close()
//将文件写到本地
_, err = io.Copy(newFile, file)
if err != nil {
_, _ = io.WriteString(w, "Write file error")
return
}
_,_ = io.WriteString(w, "Upload success")
}
复制代码文件下载处理器
func handleDownload (w http.ResponseWriter, request *http.Request) {
//文件上传只允许GET方法
if request.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("Method not allowed"))
return
}
//文件名
filename := request.FormValue("filename")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
log.Println("filename: " + filename)
//打开文件
file, err := os.Open(BaseUploadPath + "/" + filename)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
//结束后关闭文件
defer file.Close()
//设置响应的header头
w.Header().Add("Content-type", "application/octet-stream")
w.Header().Add("content-disposition", "attachment; filename=\""+filename+"\"")
//将文件写至responseBody
_, err = io.Copy(w, file)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
}
复制代码参考资料:golang.org/pkg/