Scan and Upload Documents in Web TWAIN and Go

Last week, I introduced how to create a Web application for document imaging and uploading with Dynamic Web TWAIN SDK and Node.js. In this tutorial, I’d like to share a more convenient way to implement such a solution in Go. You can just copy the client-relevant resources and page files to the new project since there’s no change at all.

go_dwt

Download and Installation

Creating a Web Server in Go

Create a file server.go, and open it in your editor. Add the main function:

func main() {
	http.HandleFunc("/", handFile) // loading Web resources
	http.HandleFunc("/upload", uploadHandler) // receiving uploaded files
	http.ListenAndServe(":2014", nil) // port number
}
  • The function handFile is used to load Web resources (HTML, CSS and etc.).
  • The function uploadHandler is used to receive the uploaded images.
  • 2014 is the port number.

In the function handFile, load the static Web page index.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)
	}
}

Once the uploaded images are received on the server side, we need to extract some useful information from the multipart form data. In Node.js, I downloaded an extra Node.js module for assistance, whereas the Golang simplifies the work. In the function uploadHandle, use Go APIs to parse the multipart form data and save the uploaded images to your 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(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
		 }
	}
}

That’s all. The cross-domain access is also supported by default. If you have no idea about how to write the Web client, please read Document Imaging and Uploading with Dynamic Web TWAIN and Node.js

Now, run the server:

go run server.go

Visit http://localhost:2014.

Source Code

https://github.com/DynamsoftRD/go-dwt

git clone https://github.com/DynamsoftRD/go-dwt