golang 实现文件上传下载

Gin框架上传下载

上传(支持批量上传)
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("保存文件失败")
			}
		}
	})

下载

httpRouter.GET("/download", func(ctx *gin.Context) {
		filePath := ctx.Query("url")
		//打开文件
		file, err := os.Open("./" + filePath)
		if err != nil {
			fmt.Println("打开文件错误", err)
		}
		defer file.Close()

		//获取文件的名称
		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)
	})

原生的上传下载

上传(支持批量上传)
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseMultipartForm(20); err != nil {
			fmt.Println("解析url失败", err)
		}
		if r.Method == "GET" {
			files, err := template.ParseFiles("fileName")
			if err != nil {
				fmt.Println("解析文件失败", 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("创建文件失败")
				}
				file, err := v.Open()
				if err != nil {
					fmt.Println("打开文件失败")
				}
				_, err = io.Copy(f, file)
				if err != nil {
					fmt.Println("拷贝文件数据失败")
				}
			}
			w.Write([]byte("upload success"))
		}
	})
下载
http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			fmt.Println("解析url失败", err)
		}
		fileName := r.Form["fileName"][0]
		filePath := "./" + fileName
		_, err := os.Stat(filePath)
		if err != nil || os.IsNotExist(err) {
			fmt.Println("文件不存在", err)
		}
		bytes, err := os.ReadFile(filePath)
		if err != nil {
			fmt.Println("读取文件失败", err)
		}
		w.Header().Add("Content-Type", "application/octet-stream")
		w.Header().Add("Content-Disposition", "attachment; filename= "+fileName)
		w.Write(bytes)
	})

github个人博客

https://wangyufenggogogo.github.io

你可能感兴趣的:(go)