老鐵門還是相同的人物,相同的地點(diǎn),不同的時(shí)間,直接上代碼,啊哈哈哈
package main
import (
"fmt"
"io"
"net/http"
"os"
)
/*
文件上傳處理
*/
func uploadFile(w http.ResponseWriter, r *http.Request) {
// Parse the multipart form data
err := r.ParseMultipartForm(10 << 20) // 最大10MB文件大小
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 獲取上傳的文件
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// 創(chuàng)建一個(gè)新文件
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
// 將上傳的文件內(nèi)容拷貝到新文件中
_, err = io.Copy(f, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "文件上傳成功!")
}
/*
文件下載
*/
func downloadFile(w http.ResponseWriter, r *http.Request) {
// 獲取URL中的參數(shù)(Get請(qǐng)求)
queryParams := r.URL.Query()
// 獲取特定的值(拿到需要下載的文件名稱)
filePath := queryParams.Get("filename")
if filePath == "" {
// 直接返回響應(yīng)
fmt.Fprintf(w, "%s", "文件名不能為空!")
return
}
// 和 OS 交互
file, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
fmt.Fprintf(w, "Sorry:%s", "找不到對(duì)應(yīng)的文件!")
return
}
defer file.Close()
// 設(shè)置響應(yīng)頭,告訴瀏覽器該文件需要下載而不是直接展示
w.Header().Set("Content-Disposition", "attachment; filename="+filePath)
// 將文件內(nèi)容寫入響應(yīng)體
_, err = io.Copy(w, file)
if err != nil {
fmt.Println(err)
return
}
}
func main() {
// 上傳 (參數(shù)說明:接口地址和調(diào)用的是那個(gè)函數(shù))
http.HandleFunc("/upload", uploadFile)
// 下載
http.HandleFunc("/download", downloadFile)
http.ListenAndServe(":8080", nil)
}