Go Web Application File upload / download

スポンサーリンク

File upload

To handle file upload, we need to handle multipart/form-data

Sample code structure

|-web
|  |- filehandler.go
main.go

filehandler.go

File Upload part

package web

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

/* multipart/form-data */

/* Upload File */
func UploadFileHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(5 << 20)                      // Max memory 5MB
	file, handler, err := r.FormFile("uploadFileName") // form key
	if err != nil {
		fmt.Println("error reading file from request")
		return
	}
	defer file.Close()
	f, err := os.OpenFile("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) // Save file under current dir
	if err != nil {
		fmt.Println("error create file")
		return
	}
	defer f.Close()
	io.Copy(f, file) // test with postman
}

How to test

Postman supports file upload with POST.
Let’s try

Select post and fill URL

Goes to “Body” tab and select “form-data” and add

Key and Value

Select “File” to upload file and value button has “Select Files” to choose files.

File download

Open file from local.

Set content type and Copy file to writer.

filehandler.go

Download part

/* Download File */
func DownloadFileHandler(w http.ResponseWriter, r *http.Request) {
	filename := "main.go"
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println("error reading file")
		return
	}
	fi, err := file.Stat()
	if err != nil {
		fmt.Println("error reading file stat")
		return
	}
	defer file.Close()
	w.Header().Set("Content-Disposition", "attchment; filename="+filename)
	w.Header().Set("Conetnt-Type", "text/plain")
	w.Header().Set("Content-Length", string(fi.Size()))
	io.Copy(w, file)
}

main

Last, to use above 2 functions, let’s create end point.

package main

import (
	"log"
	"net/http"
	"github.com/DJ110/gorefs/web"
)

func main() {

        http.HandleFunc("/file/upload", web.UploadFileHandler)
	http.HandleFunc("/file/download", web.DownloadFileHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

To test upload, please check Postman part. URL is localhost:8080/file/upload

Download is simple. Just goes to localhost:8080/file/download with browser, you can download main.go file

golang
スポンサーリンク
Professional Programmer2

コメント