- Go Web Development Cookbook
- Arpit Aggarwal
- 319字
- 2021-08-27 19:01:19
How to do it…
In this recipe, we are going to create an HTML form with a field of type file, which lets the user pick one or more files to upload to a server via a form submission. Perform the following steps:
- Create upload-file.html inside the templates directory, as follows:
$ mkdir templates && cd templates && touch upload-file.html
- Copy the following content to upload-file.html:
<html>
<head>
<meta charset="utf-8">
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/
form-data">
<label for="file">File:</label>
<input type="file" name="file" id="file">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
In the preceding template, we defined a field of type file along with a Submit button.
On clicking the Submit button, the client encodes the data that forms the body of the request and makes a POST call to the form action, which is /upload in our case.
- Create upload-file.go, where we will define handlers to render the file upload template, get the file from the request, process it, and write the response to an HTTP response stream, as follows:
package main
import
(
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
func fileHandler(w http.ResponseWriter, r *http.Request)
{
file, header, err := r.FormFile("file")
if err != nil
{
log.Printf("error getting a file for the provided form key : ",
err)
return
}
defer file.Close()
out, pathError := os.Create("/tmp/uploadedFile")
if pathError != nil
{
log.Printf("error creating a file for writing : ", pathError)
return
}
defer out.Close()
_, copyFileError := io.Copy(out, file)
if copyFileError != nil
{
log.Printf("error occurred while file copy : ", copyFileError)
}
fmt.Fprintf(w, "File uploaded successfully : "+header.Filename)
}
func index(w http.ResponseWriter, r *http.Request)
{
parsedTemplate, _ := template.ParseFiles("templates/
upload-file.html")
parsedTemplate.Execute(w, nil)
}
func main()
{
http.HandleFunc("/", index)
http.HandleFunc("/upload", fileHandler)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
With everything in place, the directory structure should look like the following:

- Run the program with the following command:
$ go run upload-file.go
推薦閱讀
- 數(shù)據(jù)通信網(wǎng)絡(luò)實踐:基礎(chǔ)知識與交換機技術(shù)
- 物聯(lián)網(wǎng)識別技術(shù)
- 計算機網(wǎng)絡(luò)安全實訓(xùn)教程(第二版)
- Go Web Scraping Quick Start Guide
- Socket.IO Real-time Web Application Development
- Mastering JavaFX 10
- 物聯(lián)網(wǎng)通信技術(shù)
- 城市治理一網(wǎng)統(tǒng)管
- 計算機網(wǎng)絡(luò)技術(shù)及應(yīng)用
- 圖解物聯(lián)網(wǎng)
- 區(qū)塊鏈技術(shù)與應(yīng)用:打造分布式商業(yè)新生態(tài)
- 網(wǎng)絡(luò)互聯(lián)技術(shù)(理論篇)
- Migrating to Drupal7
- Architecting Data:Intensive Applications
- 通信系統(tǒng)實戰(zhàn)筆記:無處不在的信號處理