Scanning and Uploading Documents with Dynamic Web TWAIN and Go
In the previous article, we demonstrated the implementation of a web application for scanning and uploading documents using Dynamic Web TWAIN and Node.js. In this article, we will guide you through achieving the same functionality using Go. The process closely mirrors the Node.js implementation, allowing you to reuse client-side resources and page files in your new project.
This article is Part 3 in a 3-Part Series.
Prerequisites
Create a Web Server with Go for Image Uploading
- Create a file named server.go.
-
Within the file, import the necessary packages:
fmt
,io
,net/http
, andos
.package main import ( "fmt" "io" "net/http" "os" )
- fmt is used for formatting and printing.
- io provides the basic interfaces for I/O primitives.
- net/http provides HTTP client and server implementations.
- os provides a platform-independent interface to operating system functionality.
- Define the main function to configure and initiate the server.
func main() { http.HandleFunc("/", handFile) // loading Web resources http.HandleFunc("/upload", uploadHandler) // receiving uploaded files http.ListenAndServe(":2024", nil) // port number }
- The function
handFile
loads the static web pageindex.html
.func handFile(w http.ResponseWriter, r *http.Request) { if (r.URL.Path == "/") { http.ServeFile(w, r, "./index.html") } else { http.ServeFile(w, r, "." + r.URL.Path) } }
-
The function
uploadHandler
receives uploaded images and saves them to the local disk. Compared to the Node.js implementation, the Go implementation is more concise and straightforward, thanks to the Go APIs that simplify the process of parsing multipart form data and saving the uploaded images to the local disk.func uploadHandler(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(2000) if err != nil { fmt.Fprintln(w, err) return } formdata := r.MultipartForm files := formdata.File["RemoteFile"] for i := range files { file, err := files[i].Open() defer file.Close() if err != nil { fmt.Fprintln(w, err) return } out, err := os.Create("UploadedImages/" + files[i].Filename) defer out.Close() if err != nil { fmt.Fprintf(w, "create file err!") return } _, err = io.Copy(out, file) if err != nil { fmt.Fprintln(w, err) return } } }
2024
is the designated port number.
- The function
-
Run the server, then navigate to http://localhost:2024 in your web browser.
go run server.go
Reusing Client-Side Resources
The client-side resources, including the HTML file and JavaScript code, can be reused in the Go project. Simply copy the code from the previous article and integrate it into the HTML file.
https://github.com/yushulx/Scan-Documents-with-Go/blob/master/index.html
The license key needs to be updated in the JavaScript code.
Dynamsoft.DWT.ProductKey = 'LICENSE-KEY';