如何使用Golang实现文件上传和下载
时间:2023-06-27 14:09:20 389浏览 收藏
大家好,今天本人给大家带来文章《如何使用Golang实现文件上传和下载》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
在Web开发中,文件上传和下载是非常常见的功能。本文将介绍如何使用Golang实现文件上传和下载。
一、文件上传
1.1 实现步骤
- 创建路由处理函数
使用Golang实现文件上传,需要先创建一个路由处理函数来处理上传文件的请求。
func uploadFile(w http.ResponseWriter, r *http.Request) { // 处理上传文件的代码 }
- 解析上传文件
接下来,需要解析上传文件。可以使用multipart/form-data格式来解析文件。
err := r.ParseMultipartForm(32 << 20) // 文件最大32MB if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } file, _, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer file.Close()
- 保存上传文件
最后,把上传的文件保存到本地。
err = os.MkdirAll("uploads", 0755) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } f, err := os.Create(filepath.Join("uploads", header.Filename)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() io.Copy(f, file) w.Write([]byte("File uploaded successfully."))
完整代码如下:
func uploadFile(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(32 << 20) // 文件最大32MB if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } file, header, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer file.Close() err = os.MkdirAll("uploads", 0755) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } f, err := os.Create(filepath.Join("uploads", header.Filename)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() io.Copy(f, file) w.Write([]byte("File uploaded successfully.")) }
1.2 完整代码
package main import ( "io" "net/http" "os" "path/filepath" ) func uploadFileHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: // 显示上传文件的表单 w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(``)) case http.MethodPost: // 解析上传文件 err := r.ParseMultipartForm(32 << 20) // 文件最大32MB if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } file, header, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer file.Close() // 保存上传文件 err = os.MkdirAll("uploads", 0755) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } f, err := os.Create(filepath.Join("uploads", header.Filename)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() io.Copy(f, file) w.Write([]byte("File uploaded successfully.")) default: http.Error(w, "Invalid request method.", http.StatusMethodNotAllowed) } } func main() { http.HandleFunc("/upload", uploadFileHandler) http.ListenAndServe(":8888", nil) }Upload file
二、文件下载
2.1 实现步骤
- 创建路由处理函数
使用Golang实现文件下载,需要先创建一个路由处理函数来处理下载文件的请求。
func downloadFile(w http.ResponseWriter, r *http.Request) { // 处理下载文件的代码 }
- 设置响应头
在处理下载文件的请求时,需要设置响应头,告诉浏览器下载的文件的类型和文件名。
w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
其中,Content-Type表示下载文件的类型,Content-Disposition表示下载文件的方式和文件名。
- 把文件内容写入响应
最后,把文件的内容写入响应,让浏览器下载文件。
http.ServeFile(w, r, filePath)
完整代码如下:
func downloadFile(w http.ResponseWriter, r *http.Request) { fileName := "example.txt" filePath := filepath.Join("uploads", fileName) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename="+fileName) http.ServeFile(w, r, filePath) }
2.2 完整代码
package main import ( "net/http" "path/filepath" ) func downloadFileHandler(w http.ResponseWriter, r *http.Request) { fileName := "example.txt" filePath := filepath.Join("uploads", fileName) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename="+fileName) http.ServeFile(w, r, filePath) } func main() { http.HandleFunc("/download", downloadFileHandler) http.ListenAndServe(":8888", nil) }
三、完整代码
package main import ( "io" "net/http" "os" "path/filepath" ) func uploadFileHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: // 显示上传文件的表单 w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(``)) case http.MethodPost: // 解析上传文件 err := r.ParseMultipartForm(32 << 20) // 文件最大32MB if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } file, header, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer file.Close() // 保存上传文件 err = os.MkdirAll("uploads", 0755) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } f, err := os.Create(filepath.Join("uploads", header.Filename)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() io.Copy(f, file) w.Write([]byte("File uploaded successfully.")) default: http.Error(w, "Invalid request method.", http.StatusMethodNotAllowed) } } func downloadFileHandler(w http.ResponseWriter, r *http.Request) { fileName := "example.txt" filePath := filepath.Join("uploads", fileName) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename="+fileName) http.ServeFile(w, r, filePath) } func main() { http.HandleFunc("/upload", uploadFileHandler) http.HandleFunc("/download", downloadFileHandler) http.ListenAndServe(":8888", nil) }Upload file
至此,使用Golang实现文件上传和下载的方法介绍完毕。
文中关于golang,文件上传,文件下载的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何使用Golang实现文件上传和下载》文章吧,也可关注golang学习网公众号了解相关技术文章。
相关阅读
更多>
-
505 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
416 收藏
-
189 收藏
-
213 收藏
-
315 收藏
-
381 收藏
-
128 收藏
-
236 收藏
-
340 收藏
-
298 收藏
-
249 收藏
-
460 收藏
-
495 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习