如何使用Golang实现文件上传和下载
2023-06-27 14:09:20
0浏览
收藏
大家好,今天本人给大家带来文章《如何使用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(`
Upload file
`))
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)
}二、文件下载
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(`
Upload file
`))
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)
}至此,使用Golang实现文件上传和下载的方法介绍完毕。
文中关于golang,文件上传,文件下载的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何使用Golang实现文件上传和下载》文章吧,也可关注golang学习网公众号了解相关技术文章。
golang中如何验证输入是否为英文字母
- 上一篇
- golang中如何验证输入是否为英文字母
- 下一篇
- Golang中如何使用缓存提高游戏应用程序性能?
查看更多
最新文章
-
- Golang · Go教程 | 9小时前 | HTTP · Go教程 · 问题排查 · io.ReadAll · JSON绑定 · Go教程 Go HTTP请求体 io.ReadAll Request Body JSON绑定
- Go HTTP 请求体为什么只能读一次:io.ReadAll 后绑定参数为空怎么排查
- 244浏览 收藏
-
- Golang · Go教程 | 12小时前 |
- Go 1.22 循环变量变化:for range 闭包坑为什么少了
- 238浏览 收藏
-
- Golang · Go教程 | 13小时前 |
- Go slog 结构化日志怎么接入:从 fmt 打印到可检索字段
- 217浏览 收藏
-
- Golang · Go教程 | 4天前 |
- Go 接口防重复提交:用 Idempotency-Key 处理按钮连点和网络重试
- 367浏览 收藏
-
- Golang · Go教程 | 5天前 | HTTP · 文件上传 · Go教程 · 资源预算 · multipart · 文件上传 临时文件 ParseMultipartForm multipart Go教程 MaxBytesReader 资源预算
- Go 文件上传接口怎么做资源预算:限制大小、内存和临时文件
- 237浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ljg-skills
- ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
- 4369次使用
-
- MELO音乐
- MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
- 4048次使用
-
- UniScribe
- UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
- 4037次使用
-
- 剧云
- 剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
- 4221次使用
-
- 万象有声
- 万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
- 4190次使用
查看更多
相关文章
-
- Java 性能优化上线清单:从定位、改造到灰度发布
- 2026-06-11 860浏览
-
- Spring Boot 压测验证:Gatling、JMeter 与性能回归门禁
- 2026-06-11 843浏览
-
- Java NMT 非堆内存排查:Direct Buffer、线程栈与 Metaspace 分析
- 2026-06-11 826浏览
-
- Spring Boot 容器内存优化:JVM 堆、非堆与 MaxRAMPercentage
- 2026-06-11 809浏览
-
- Tomcat 连接与线程参数调优:maxThreads、acceptCount 与 KeepAlive
- 2026-06-11 792浏览

