最近公司弃用企业级的某盘,因为资料泄露的缘故,让我我搞一个类似的东西供内部使用,所以就一边写博客一边写思路吧
开始想用Python来写,使用Django框架,但是觉得有些臃肿,并且上传文件等涉及到io操作,大量用户觉得不太行,索性就用go来写
package main
import (
"filestore-server/handler"
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/file/upload", handler.UploadHandler)
http.HandleFunc("/file/upload/suc", handler.UploadSucHandler)
err := http.ListenAndServe("localhost:8080", nil)
if err != nil {
fmt.Printf("Failed reseaon %s", err)
}
}
package handler
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
// 处理文件上传
func UploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
// 返回上传html页面
if data, err := ioutil.ReadFile("./static/view/index.html"); err != nil {
io.WriteString(w, "error of read file")
return
} else {
io.WriteString(w, string(data))
}
} else if r.Method == "POST" {
// 接收文件流及存储到本地目录
file, head, err := r.FormFile("file")
if err !=nil {
fmt.Printf("Failed to get data,err:%s\n", err)
return
}
defer file.Close()
newFile, err := os.Create("/Users/jack_zhou/coding_test" + head.Filename)
if err != nil {
fmt.Printf("Filed to create file")
return
}
defer newFile.Close()
_, err = io.Copy(newFile, file) // 忽略返回的字节长度
if err != nil {
fmt.Printf("Failed to save data into file, err%s", err.Error())
http.Error(w, err.Error(),http.StatusInternalServerError)
return
}
http.Redirect(w,r,"/file/upload/suc", http.StatusFound)
}
}
// 上传已完成
func UploadSucHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Upload finished")
}
先看一下效果
速度简直是秒传啊
(更新与4月4日晚11.59)
原文:https://www.cnblogs.com/zhoulixiansen/p/12640080.html