Efficient Multiple File Upload Handling in Golang

Estimated read time 3 min read

Introduction:

Handling multiple file uploads is a common requirement in web applications. Golang provides a robust set of tools and libraries for efficiently managing file uploads. In this article, we’ll explore how to handle multiple file uploads in a Golang web application. We’ll cover both the server-side handling and the client-side form setup.

1. Server-Side Handling:

1.1 Setup Your Golang Web Server:

Ensure you have a web server set up using a Golang web framework. For this example, we’ll use Gin, a lightweight web framework.

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.POST("/upload", func(c *gin.Context) {
        // Handle file uploads here
    })

    router.Run(":8080")
}

1.2 Handle File Uploads:

To handle multiple file uploads, you can use the MultipartForm function provided by the gin.Context object.

router.POST("/upload", func(c *gin.Context) {
    form, err := c.MultipartForm()
    if err != nil {
        c.JSON(500, gin.H{"error": "Error parsing form"})
        return
    }

    files := form.File["files"]
    for _, file := range files {
        err := c.SaveUploadedFile(file, "uploads/"+file.Filename)
        if err != nil {
            c.JSON(500, gin.H{"error": "Error saving file"})
            return
        }
    }

    c.JSON(200, gin.H{"message": "Files uploaded successfully"})
})

In this example, we assume the uploaded files are stored in the “uploads” directory. Adjust the file path as needed for your application.

2. Client-Side Setup:

2.1 Create an HTML Form:

Create an HTML form that allows users to select multiple files for uploading. Ensure the form’s enctype is set to "multipart/form-data".

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Upload</title>
</head>
<body>
    <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
        <label for="files">Select multiple files:</label>
        <input type="file" id="files" name="files" multiple>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

2.2 Add Client-Side JavaScript (Optional):

You can enhance the user experience by adding some client-side JavaScript to display the selected file names.

<!-- Add this script in the head or body of your HTML -->
<script>
    document.getElementById("files").addEventListener("change", function() {
        const files = document.getElementById("files").files;
        const fileNames = Array.from(files).map(file => file.name);
        document.getElementById("selected-files").innerText = "Selected Files: " + fileNames.join(", ");
    });
</script>

2.3 Testing the Setup:

  1. Run your Golang server.
  2. Open the HTML form in a browser.
  3. Select multiple files.
  4. Submit the form to trigger the file upload.

Conclusion:

Handling multiple file uploads in Golang is straightforward with the help of web frameworks like Gin. The server-side code efficiently processes the uploaded files, and the client-side form setup allows users to select and upload multiple files seamlessly. Tailor this example to fit your specific application needs, and you’ll have a reliable and efficient solution for handling multiple file uploads in your Golang web application. Happy coding!

Related Articles