To create and use HTML forms with file uploads in Go, follow these steps:
import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Parse the form data
r.ParseMultipartForm(10 << 20) // 10MB
// Access the uploaded file
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// Create a new file on the server
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
// Copy the uploaded file data to the new file
io.Copy(f, file)
fmt.Fprintf(w, "File uploaded successfully!")
} else {
// Display the upload form
tmpl, _ := template.ParseFiles("upload.html")
tmpl.Execute(w, nil)
}
}
func main() {
http.HandleFunc("/upload", uploadHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
upload.html
) that includes a file input field:<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
http://localhost:8080/upload
in your browser. You should see the upload form. Select a file to upload, and click the "Upload" button.This implementation sets up a simple HTTP server in Go that can handle file uploads. When a file is uploaded, it is saved to the server with the same filename as the uploaded file.
Note: Ensure that you have appropriate error handling and security measures in place when implementing file uploads in a production environment.