使用io包和net包實(shí)現(xiàn)基于http的文件上傳下載
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 結(jié)束時關(guān)閉文件
defer file.Close()
log.Println("filename: " + fileHeader.Filename)
//創(chuàng)建文件
newFile, err := os.Create( "./" + fileHeader.Filename)
if err != nil {
_, _ = io.WriteString(w, "Create file error")
return
}
//defer 結(jié)束時關(guān)閉文件
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
}
//結(jié)束后關(guān)閉文件
defer file.Close()
//設(shè)置響應(yīng)的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
}
}