hcmp/weapp/wxfile.go
2024-07-31 15:48:23 +08:00

48 lines
1.4 KiB
Go

package weapp
import (
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/shockliu/logger"
)
// 下载链接 https://www.daymele.com/mapp/download/recharge.xls
func Download(w http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/favicon.ico" {
return
}
pos := strings.LastIndex(req.RequestURI, "/") + 1
logger.Debugf("Download:%s\n", req.RequestURI)
filename := req.RequestURI[pos:]
enEscapeUrl, err := url.QueryUnescape(filename)
if err != nil {
logger.Errorf("下载文件获取文件名失败:%s\n", err)
w.Write([]byte("暂时无法下载您所需要的文件,请确认文件名称或联系管理员"))
return
}
logger.Debugf("Content:%s\n", enEscapeUrl)
f, err := os.Open("/home/share/" + enEscapeUrl)
if err != nil {
logger.Errorf("下载文件打开失败:%s\n", err)
w.Write([]byte("暂时无法下载您所需要的文件,请确认文件名称或联系管理员"))
return
}
info, err := f.Stat()
if err != nil {
logger.Errorf("下载文件状态失败:%s\n", err)
w.Write([]byte("暂时无法下载您所需要的文件,请确认文件名称或联系管理员"))
return
}
contentType := "application/octet-stream"
w.Header().Set("content-Disposition", "attachment;filename="+filename)
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
f.Seek(0, 0)
io.Copy(w, f)
}