完成文件上传链接生成功能

This commit is contained in:
2023-12-19 17:31:30 +08:00
parent 42c764f825
commit ee9aeb4820
5 changed files with 218 additions and 19 deletions

66
main.go
View File

@@ -11,6 +11,7 @@ import (
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"time"
)
@@ -31,7 +32,6 @@ func init() {
`
fmt.Println(appinfo)
database.Initdb() //初始化数据库
dirPath := "./data/img"
// 使用 os.Stat 检查目录是否存在
@@ -39,7 +39,7 @@ func init() {
if os.IsNotExist(err) {
// 目录不存在,可以调用 os.Mkdir 创建
err := os.Mkdir(dirPath, 0755)
err := os.MkdirAll(dirPath, 0755)
if err != nil {
fmt.Println("无法创建目录:", err)
return
@@ -52,18 +52,28 @@ func init() {
// 发生其他错误
fmt.Println("发生错误:", err)
}
database.Initdb() //初始化数据库
fmt.Println("数据库初始化完成")
}
func main() {
http.HandleFunc("/upload", upload) //设置访问的路由
http.HandleFunc("/info", showimg)
http.HandleFunc("/upload", upload)
http.HandleFunc("/img/",downloadHandler)//设置访问的路由
fmt.Println("Web服务器已启动")
err := http.ListenAndServe(":9090", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func showimg(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("Web/info.html")
t.Execute(w, "Hello")
}
// 处理/upload 逻辑
func upload(w http.ResponseWriter, r *http.Request) {
@@ -116,8 +126,9 @@ func upload(w http.ResponseWriter, r *http.Request) {
io.Copy(f, file)
// 存入数据库
database.NewFile(RandomString(10),md5sum)
var linkid = RandomString(10)
database.NewFile(linkid,md5sum,ext)
w.Write([]byte(linkid))
}
}
@@ -131,3 +142,46 @@ func RandomString(n int) string {
}
return string(bytes)
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
// 获取请求参数,例如文件名
filename := r.FormValue("id")
if filename == "" {
http.Error(w, "未提供文件名", http.StatusBadRequest)
return
}
// 拼接文件路径,确保路径安全性
filePath := filepath.Join("./data/img", database.GetFileName(filename))
// 打开文件
file, err := os.Open(filePath)
if err != nil {
http.Error(w, "文件未找到", http.StatusNotFound)
return
}
defer file.Close()
// 获取文件信息
fileInfo, err := file.Stat()
if err != nil {
http.Error(w, "无法获取文件信息", http.StatusInternalServerError)
return
}
// 设置响应头,告诉浏览器直接显示文件
w.Header().Set("Content-Disposition", "inline; filename="+filename)
w.Header().Set("Content-Type", "image/jpeg") // 适用于 JPEG 图片,根据实际文件类型设置
// 将文件内容拷贝到响应体中
http.ServeContent(w, r, filename, fileInfo.ModTime(), file)
}
// 辅助函数,获取文件大小
func fileSize(file *os.File) int64 {
stat, err := file.Stat()
if err != nil {
return 0
}
return stat.Size()
}