当前位置:网站首页>Golang realizes file upload and download
Golang realizes file upload and download
2022-07-29 10:59:00 【wangwei830】
Gin Frame upload and download
Upload ( Support bulk upload )
httpRouter.POST("/upload", func(ctx *gin.Context) {
forms, err := ctx.MultipartForm()
if err != nil {
fmt.Println("error", err)
}
files := forms.File["fileName"]
for _, v := range files {
if err := ctx.SaveUploadedFile(v, fmt.Sprintf("%s%s", "./file/", v.Filename)); err != nil {
fmt.Println(" Failed to save file ")
}
}
})
download
httpRouter.GET("/download", func(ctx *gin.Context) {
filePath := ctx.Query("url")
// Open file
file, err := os.Open("./" + filePath)
if err != nil {
fmt.Println(" Error opening file ", err)
}
defer file.Close()
// Get the name of the file
fileName := path.Base(filePath)
ctx.Header("Content-Type", "application/octet-stream")
ctx.Header("Content-Disposition", "attachment; url="+fileName)
ctx.Header("Content-Transfer-Encoding", "binary")
ctx.Header("Cache-Control", "no-cache")
ctx.File("./" + filePath)
})
Native upload and download
Upload ( Support bulk upload )
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(20); err != nil {
fmt.Println(" analysis url Failure ", err)
}
if r.Method == "GET" {
files, err := template.ParseFiles("fileName")
if err != nil {
fmt.Println(" Failed to parse file ", err)
}
files.Execute(w, nil)
} else {
files := r.MultipartForm.File["fileName"]
for _, v := range files {
f, err := os.Create("./file/" + v.Filename)
if err != nil {
fmt.Println(" Failed to create file ")
}
file, err := v.Open()
if err != nil {
fmt.Println(" fail to open file ")
}
_, err = io.Copy(f, file)
if err != nil {
fmt.Println(" Failed to copy file data ")
}
}
w.Write([]byte("upload success"))
}
})
download
http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
fmt.Println(" analysis url Failure ", err)
}
fileName := r.Form["fileName"][0]
filePath := "./" + fileName
_, err := os.Stat(filePath)
if err != nil || os.IsNotExist(err) {
fmt.Println(" file does not exist ", err)
}
bytes, err := os.ReadFile(filePath)
if err != nil {
fmt.Println(" Failed to read file ", err)
}
w.Header().Add("Content-Type", "application/octet-stream")
w.Header().Add("Content-Disposition", "attachment; filename= "+fileName)
w.Write(bytes)
})
github Personal blog
https://wangyufenggogogo.github.io
边栏推荐
- Meeting OA project (V) -- meeting notice and feedback details
- 面试中项目讲解的步骤
- sql join中on条件后接and和where
- Kunlunbase instruction manual (II) best practices for peer-to-peer deployment
- ES6 arrow function this points to
- 阿里P8爆出的这份大厂面试指南,看完工资暴涨30k!
- 基本.分块
- Niuke net brush questions
- LeetCode_ 1049_ Weight of the last stone II
- 建议收藏丨sql行转列的一千种写法!!
猜你喜欢

Starrocks technology insider: how to have both real-time update and fast query

Pytorch 入门

ECCV 2022 | ssp: a new idea of small sample tasks with self-supporting matching

2022最新 wifi大师小程序独立版3.0.8

Learning R language these ebooks are enough!

AI模型风险评估 第2部分:核心内容

牛客网刷题

Factoextra: visual PCA of multivariate statistical methods

Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29

Analysis of QT basic engineering
随机推荐
ECCV 2022 | SSP: 自支持匹配的小样本任务新思想
【图像处理】基于中轴变换实现图像骨架提取附matlab代码
LeetCode二叉树系列——144.二叉树的前序遍历
Ggdag draw DAG and cause and effect diagram
Start from scratch blazor server (3) -- add cookie authorization
How to synchronize when the primary and sub warehouses are modified?
DOD and Dor, two artifacts to reduce "cognitive bias"
周鸿祎:360是世界上最大的安全大数据公司
阿里P8爆出的这份大厂面试指南,看完工资暴涨30k!
Spark efficient data analysis 01. Establishment of idea development environment
Function comparison between report control FastReport and stimulus soft
matplotlib中文问题
LeetCode_ 416_ Divide equal sum subsets
[unity, C #] character keyboard input steering and rotation
Kunlunbase instruction manual (III) data import & synchronization
Learning R language these ebooks are enough!
GBase8s Informix Dodker 高可用集群自恢复集群启动命令oninitdb的设计与实现
Using Riemann sum to calculate approximate integral in R language
Kunlunbase instruction manual (II) best practices for peer-to-peer deployment
小笑授权系统V5.0开心版