当前位置:网站首页>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
边栏推荐
- Peking University open classes are coming! Welcome to the "AI for science" class
- 小笑授权系统V5.0开心版
- 基于flask实现的mall商城---用户模块
- 就这?TypeScript其实并不难!(建议收藏)
- [unity, C #] character keyboard input steering and rotation
- Kunlunbase support for MySQL private DML syntax
- R language brca MRNA data set analysis
- 美团、饿了么被杭州市监约谈要求落实食品安全管理责任 严禁恶意竞争
- 开源峰会抢先看 | 7月29日分论坛&活动议程速览
- Starrocks technology insider: how to have both real-time update and fast query
猜你喜欢

Leetcode bit operation

Kunlunbase instruction manual (II) best practices for peer-to-peer deployment

自采集在线电脑壁纸php源码v2.0自适应端

Sunwenlong, Secretary General of the open atom open source foundation, worked together to expand open source

报表控件FastReport与StimulSoft功能对比

Getting started with pytoch

Site data collection -scrapy usage notes

Niuke net brush questions

浅谈安科瑞灭弧式智慧用电在养老机构的应用

Pytorch 入门
随机推荐
LeetCode_416_分割等和子集
LeetCode_278_第一个错误的版本
ECCV 2022 | ssp: a new idea of small sample tasks with self-supporting matching
Sunwenlong, Secretary General of the open atom open source foundation, worked together to expand open source
深入理解C# 进入快速通道的委托
ES6 arrow function this points to
从零开始Blazor Server(3)--添加cookie授权
Use tidymodels to solve the binary logistic model
SkiaSharp 之 WPF 自绘 弹动小球(案例版)
Learning R language these ebooks are enough!
Spark efficient data analysis 02, basic knowledge 13
建议收藏丨sql行转列的一千种写法!!
LeetCode_ 1049_ Weight of the last stone II
Spark高效数据分析01、idea开发环境搭建
LeetCode_ 278_ First wrong version
牛客网刷题
AI模型风险评估 第2部分:核心内容
多线程顺序运行的 4 种方法,面试随便问!
How to realize the function of adding watermark
Package delivery (greedy)