登录
首页 >  Golang >  Go教程

如何使用Golang实现文件上传和下载

时间:2023-06-27 14:09:20 389浏览 收藏

大家好,今天本人给大家带来文章《如何使用Golang实现文件上传和下载》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

在Web开发中,文件上传和下载是非常常见的功能。本文将介绍如何使用Golang实现文件上传和下载。

一、文件上传

1.1 实现步骤

  1. 创建路由处理函数

使用Golang实现文件上传,需要先创建一个路由处理函数来处理上传文件的请求。

func uploadFile(w http.ResponseWriter, r *http.Request) {
   // 处理上传文件的代码
}
  1. 解析上传文件

接下来,需要解析上传文件。可以使用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()
  1. 保存上传文件

最后,把上传的文件保存到本地。

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 实现步骤

  1. 创建路由处理函数

使用Golang实现文件下载,需要先创建一个路由处理函数来处理下载文件的请求。

func downloadFile(w http.ResponseWriter, r *http.Request) {
  // 处理下载文件的代码
}
  1. 设置响应头

在处理下载文件的请求时,需要设置响应头,告诉浏览器下载的文件的类型和文件名。

w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)

其中,Content-Type表示下载文件的类型,Content-Disposition表示下载文件的方式和文件名。

  1. 把文件内容写入响应

最后,把文件的内容写入响应,让浏览器下载文件。

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学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>