How to use Golang to implement Form form file upload?

WBOY
Release: 2024-06-03 22:02:00
Original
802 people have browsed it

Using the Form form to implement file upload in the Go language includes the following steps: Set the enctype="multipart/form-data" attribute in HTML and create the form. Use r.ParseMultipartForm() in Go to handle form requests. Use r.FormFile() to get the file. Save the file to the target location by creating it and using io.Copy().

如何使用 Golang 实现 Form 表单文件上传?

Use Form form to implement file upload in Go language

In web applications, form file upload is a common scenario. Golang provides a powerful HTTP package that can be used to implement this functionality easily and efficiently.

Create the form

First, create a form in the HTML page and set the enctype="multipart/form-data" attribute, which indicates that the form will contain file data:

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="上传">
</form>
Copy after login

Processing file upload

In the Go HTTP handler, use ParseMultipartForm to process form requests:

func uploadHandler(w http.ResponseWriter, r *http.Request) {
  err := r.ParseMultipartForm(32 << 20) // 设置最大文件大小为 32MB
  if err != nil {
    http.Error(w, "无法解析表单数据", http.StatusBadRequest)
    return
  }

  // 获取文件
  file, _, err := r.FormFile("file")
  if err != nil {
    http.Error(w, "无法获取上传文件", http.StatusInternalServerError)
    return
  }
  defer file.Close()

  // 保存文件
  dst, err := os.Create("uploaded_file")
  if err != nil {
    http.Error(w, "无法创建目标文件", http.StatusInternalServerError)
    return
  }
  defer dst.Close()

  if _, err := io.Copy(dst, file); err != nil {
    http.Error(w, "无法写入文件", http.StatusInternalServerError)
    return
  }

  http.Redirect(w, r, "/success", http.StatusFound)
}
Copy after login

Practical case

The following is a simple example of uploading files using Go:

package main

import (
  "fmt"
  "net/http"
  "os"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
  err := r.ParseMultipartForm(32 << 20)
  if err != nil {
    http.Error(w, "无法解析表单数据", http.StatusBadRequest)
    return
  }

  file, _, err := r.FormFile("file")
  if err != nil {
    http.Error(w, "无法获取上传文件", http.StatusInternalServerError)
    return
  }

  filename := "./uploaded_file_" + r.Form.Get("file")
  dst, err := os.Create(filename)
  if err != nil {
    http.Error(w, "无法创建目标文件", http.StatusInternalServerError)
    return
  }

  if _, err := io.Copy(dst, file); err != nil {
    http.Error(w, "无法写入文件", http.StatusInternalServerError)
    return
  }

  fmt.Fprintf(w, "文件 %s 上传成功!", filename)
}

func main() {
  http.HandleFunc("/upload", uploadHandler)
  http.ListenAndServe(":8080", nil)
}
Copy after login

In this way, you can easily implement form file upload in your Go application.

The above is the detailed content of How to use Golang to implement Form form file upload?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!