Go文件上傳下載

Go自帶不少包,本例使用io包和net包相應的API簡單實現基於http的文件上傳下載(僅爲demo)golang

定義文件存儲文件

//假設文件上傳爲本地的服務器,上傳的基礎路徑
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 {
		_, _ = io.WriteString(w, "Create file error")
		return
	}
	//defer 結束時關閉文件
	defer newFile.Close()

	//將文件寫到本地
	_, err = io.Copy(newFile, file)
	if err != nil {
		_, _ = io.WriteString(w, "Write file error")
		return
	}
	_,_ = io.WriteString(w, "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)
		_, _ = io.WriteString(w, "Bad request")
		return
	}
	log.Println("filename: " + filename)
	//打開文件
	file, err := os.Open(BaseUploadPath + "/" + filename)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = io.WriteString(w, "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)
		_, _ = io.WriteString(w, "Bad request")
		return
	}
}
複製代碼

參考資料:golang.org/pkg/服務器

相關文章
相關標籤/搜索