Home >Backend Development >Golang >How to Handle File Uploads in a Golang net/http Server?

How to Handle File Uploads in a Golang net/http Server?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 19:12:25814browse

How to Handle File Uploads in a Golang net/http Server?

How to Receive an Uploaded File Using a Golang net/http Server

When attempting to implement a simple file upload endpoint in Golang using Mux and net/http, retrieving the file data from the request body can pose a challenge. The following solution addresses this issue:

import (
    "bytes"
    "fmt"
    "io"
    "net/http"
    "strings"
)

func ReceiveFile(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(32 << 20) // limit your max input length!
    var buf bytes.Buffer
    file, header, err := r.FormFile("file") // replace "file" with the expected form field name
    if err != nil {
        panic(err)
    }
    defer file.Close()
    name := strings.Split(header.Filename, ".")
    fmt.Printf("File name %s\n", name[0])
    io.Copy(&buf, file)
    contents := buf.String()
    fmt.Println(contents)
    buf.Reset()
    return
}

This function:

  • Parses the request's multipart form.
  • Retrieves the uploaded file from the provided field name (replace "file" with your actual field name).
  • Reads the file's contents into a buffer.
  • Prints the file's name to the console.
  • Converts the buffer's contents to a string.
  • Prints the file's contents to the console.
  • Resets the buffer for potential reuse.

The above is the detailed content of How to Handle File Uploads in a Golang net/http Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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