当前位置:网站首页>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
边栏推荐
猜你喜欢

如何开始为您的 Kubernetes 应用程序编写 Helm 图表

Detailed arrangement of JVM knowledge points (long text warning)

The 2022 open atom global open source summit opened in Beijing

一文搞懂什么是二叉树(二叉树的种类、遍历方式、定义)

Getting started with pytoch

Conference OA project - my approval

为什么应该在开发环境中使用 Kubernetes

Analysis of QT basic engineering

How to use grep to display file names and line numbers before matching lines

Discussion on the application of arcing smart electricity in elderly care institutions
随机推荐
开源峰会抢先看 | 7 月 29 日分论坛 & 活动议程速览
️ 炒 股 实 战丨原 地 起 飞 ️
Conference OA project - my approval
小笑授权系统V5.0开心版
DOD and Dor, two artifacts to reduce "cognitive bias"
Kunlunbase support for MySQL private DML syntax
开源峰会抢先看 | 7月29日分论坛&活动议程速览
1.MySQL数据库的介绍
Determine whether the values of two objects are equal
Self collection online computer wallpaper PHP source code v2.0 adaptive end
Understand what a binary tree is (types, traversal methods, definitions of binary trees)
周鸿祎:360是世界上最大的安全大数据公司
带你浅聊一下PHP搭建的电商商城系统
Software testing dry goods
2.安装MySQL
LeetCode_ 278_ First wrong version
Alibaba architects spent a year sorting out the "Lucene advanced document", and you are also a big factory employee!
The heavyweight foundation awarded platinum, gold and silver donors
QT's user-defined interface (borderless and movable)
Factoextra: visual PCA of multivariate statistical methods