主题
文件上传下载
1. 文件上传
使用 r.ParseMultipartForm
解析上传的文件:
go
func uploadHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(10 << 20) // 限制最大上传大小10MB
if err != nil {
http.Error(w, "File too big", http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("uploadFile")
if err != nil {
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
dst, err := os.Create("./uploads/" + handler.Filename)
if err != nil {
http.Error(w, "Unable to save the file", http.StatusInternalServerError)
return
}
defer dst.Close()
io.Copy(dst, file)
fmt.Fprintf(w, "File uploaded successfully: %s\n", handler.Filename)
}
2. 文件下载
设置响应头实现文件下载:
go
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := "example.txt"
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeFile(w, r, "./files/"+filename)
}
文件上传和下载是 Web 应用中常见的功能,需注意安全和性能。