1. 程式人生 > 程式設計 >Go檔案上傳下載

Go檔案上傳下載

Go自帶很多包,本例使用io包和net包相應的API簡單實現基於http的檔案上傳下載(僅為demo)

定義檔案儲存檔案

//假設檔案上傳為本地的伺服器,上傳的基礎路徑
const BaseUploadPath = "/var/file"
複製程式碼

main函式中監聽http服務

func main() {
	http.HandleFunc("/upload",handleUpload)
	http.HandleFunc("/download",handleDownload)

	err := http.ListenAndServe(":3000",nil)
	if err != nil  {
		log.Fatal("Server run fail"
) } } 複製程式碼

檔案上傳處理器

func handleUpload (w http.ResponseWriter,request *http.Request)  {
	//檔案上傳只允許POST方法
	if request.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		_,_ = w.Write([]byte("Method not allowed"))
		return
	}

	//從表單中讀取檔案
	file,fileHeader,err := request.FormFile("file"
) if err != nil { _,_ = io.WriteString(w,"Read file error") return } //defer 結束時關閉檔案 defer file.Close() log.Println("filename: " + fileHeader.Filename) //建立檔案 newFile,err := os.Create(BaseUploadPath + "/" + fileHeader.Filename) if err != nil { _,"Create file error") return } //defer 結束時關閉檔案
defer newFile.Close() //將檔案寫到本地 _,err = io.Copy(newFile,file) if err != nil { _,"Write file error") return } _,"Upload success") } 複製程式碼

檔案下載處理器

func handleDownload (w http.ResponseWriter,request *http.Request) {
	//檔案上傳只允許GET方法
	if request.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		_,_ = w.Write([]byte("Method not allowed"))
		return
	}
	//檔名
	filename := request.FormValue("filename")
	if filename == "" {
		w.WriteHeader(http.StatusBadRequest)
		_,"Bad request")
		return
	}
	log.Println("filename: " + filename)
	//開啟檔案
	file,err := os.Open(BaseUploadPath + "/" + filename)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_,"Bad request")
		return
	}
	//結束後關閉檔案
	defer file.Close()

	//設定響應的header頭
	w.Header().Add("Content-type","application/octet-stream")
	w.Header().Add("content-disposition","attachment; filename=\""+filename+"\"")
	//將檔案寫至responseBody
	_,err = io.Copy(w,file)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_,"Bad request")
		return
	}
}
複製程式碼

參考資料:golang.org/pkg/