主要演示文件拖拽上傳或點擊上傳到不一樣的目錄中,提供下載和刪除功能。javascript
目錄結構:css
-main.gohtml
--share(用於分類存放上傳文件的目錄)java
--v(視圖目錄)git
---share.htmlgithub
main.gojson
//自編了一個文件共享系統,everyone可上傳下載,無權限控制,公網使用風險大,需完善 //全部文件將上傳到./share/XXX目錄下,可經過http://localhost:8080/share/XXX 訪問並下載 // package main import ( "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "github.com/kataras/iris" ) const ( upload_path string = "./share/" ) //表示一個上傳的文件 type Upfile struct { Url string //位置,如share/XXX/ Name string //文件名,如abc.doc Date string //文件時間,ModTime轉string } //表示權限 type Allow struct { UP bool //可上傳 Down bool //可下載 Del bool //可刪除 } type Updir []Upfile //表示一個目錄當中,全部上傳的文件 // 用Len Less Swap使Updir可排序,可用sort.Sort排序 func (d Updir) Len() int { return len(d) } // Date降序 func (d Updir) Less(i, j int) bool { return d[i].Date > d[j].Date } // 交換 func (d Updir) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func main() { fmt.Println("OK!請訪問 :8080/share") //啓動一個http 服務器 app := iris.New() //靜態文件服務 app.StaticWeb("/share", "./share") //註冊視圖目錄 tmpl := iris.HTML("./v", ".html") app.RegisterView(tmpl) //主頁 app.Get("/share", func(ctx iris.Context) { ctx.View("main.html") }) //下載 app.Get("/share/{path:alphabetical}", func(ctx iris.Context) { FlagAllowDel := false //容許刪除文件標誌 //URL中的路徑 reqPath := ctx.Path() //如:/share/aaa myfolder := "." + reqPath + "/" //如:./share/aaa/ //獲取執行文件路徑: rootdir, err := filepath.Abs(filepath.Dir(os.Args[0])) //如:e:\goapp\myapp createf := rootdir + reqPath + "/" //如:e:\goapp\myapp/share/aaa/ _, err = os.Stat(createf) //os.Stat獲取文件信息 //判斷文件夾path存在,不然建立之 ,絕對路徑 if os.IsNotExist(err) { os.MkdirAll(createf, os.ModePerm) } //列出目錄下的文件 var upfile Upfile fileins := make(Updir, 0) files, _ := ioutil.ReadDir(myfolder) for _, file := range files { if file.IsDir() { continue } else { upfile.Name = file.Name() upfile.Url = ctx.Path() + "/" + file.Name() upfile.Date = file.ModTime().Format("2006-01-02 15:04:05") fileins = append(fileins, upfile) } } //fmt.Println(fileins[0].Name) //倒序排序 sort.Sort(fileins) ctx.ViewData("FlagAllowDel", FlagAllowDel) ctx.ViewData("Files", fileins) // 渲染視圖文件: ./v/index.html ctx.View("share.html") }) //主頁管理,與主頁共用模板 .v/share.html app.Get("/admin/{path:alphabetical}", func(ctx iris.Context) { FlagAllowDel := true //容許刪除文件標誌 //列出目錄下的文件 var upfile Upfile fileins := make(Updir, 0) myfolder := "./share" + ctx.Path()[6:] + "/" files, _ := ioutil.ReadDir(myfolder) for _, file := range files { if file.IsDir() { continue } else { upfile.Name = file.Name() upfile.Url = ctx.Path() + "/" + file.Name() upfile.Date = file.ModTime().Format("2006-01-02 15:04:05") fileins = append(fileins, upfile) } } //fmt.Println(fileins[0].Name) //倒序排序 sort.Sort(fileins) ctx.ViewData("FlagAllowDel", FlagAllowDel) ctx.ViewData("Files", fileins) // 渲染視圖文件: ./v/index.html ctx.View("share.html") }) //上傳, 接收用XMLHttpRequest上傳的文件 app.Post("/share/{path:alphabetical}", func(ctx iris.Context) { //獲取文件內容 file, head, err := ctx.FormFile("upfile") //可參考Get時的路徑判斷pathwww是否存在,這裏省略了... myfolder := "." + ctx.Path() + "/" defer file.Close() //建立文件 fW, err := os.Create(myfolder + head.Filename) if err != nil { fmt.Println("文件建立失敗") return } defer fW.Close() _, err = io.Copy(fW, file) if err != nil { fmt.Println("文件保存失敗") return } ctx.JSON(iris.Map{"success": true, "res": head.Filename}) }) //下載,未使用 app.Get("/share/down", func(ctx iris.Context) { //無效ctx.Header("Content-Disposition", "attachment;filename=FileName.txt") ctx.ServeFile("./share/1.txt", false) }) //刪除 app.Post("/admin/{dir}", func(ctx iris.Context) { path := ctx.PostValue("path") //如 /admin/aaa/111.txt myfolder := "./share" + path[6:] fmt.Println(myfolder) os.Remove(myfolder) ctx.JSON(iris.Map{"success": true, "res": "aaaaaaaaaaaa"}) }) app.Run(iris.Addr(":8080")) }
share.html服務器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{.Title}}</title> <style> .file_upload_box { display: inline-block; width: 200px; height: 50px; position: relative; overflow: hidden; } .file_upload_box input[type=file] { position: absolute; left: 0; top: 0; width: 100%; line-height: 50px; opacity: 0; cursor: pointer; } .file_upload_box a { display: inline-block; width: 100%; line-height: 50px; text-align: center; font-family: "Microsoft yahei"; background-color: #f60; color: #FFF; font-weight: 700; text-decoration: none; } .flexcontainer{ display:flex; } </style> </head> <body> <div class="flexcontainer"> {{if $.FlagAllowDel}} <span>管理面板</span> {{else}} <div id="fileSpan" style="background-color:#FFE;width:100%;height:50px">請將文件拖到這裏上傳(覆蓋同名文件)</div> <div class="file_upload_box"> <input type="file" name="file" onchange="upload(this)"/> <a href="#none">上傳文件</a> </div> {{end}} </div> <script type="text/javascript"> window.onload = function(){ var uuz = document.getElementById('fileSpan'); uuz.ondragenter = function(e){ e.preventDefault(); } uuz.ondragover = function(e){ e.preventDefault(); this.innerHTML = '請鬆開鼠標'; this.style.cssText="background-color:#EFF;width:100%;height:50px;" } uuz.ondragleave = function(e){ e.preventDefault(); this.innerHTML = '請將文件拖到這裏上傳'; this.style.cssText="background-color:#FFE;width:100%;height:50px;" } uuz.ondrop = function(e){ e.preventDefault(); this.innerHTML = '請將文件拖到這裏上傳'; var upfile = e.dataTransfer.files[0]; //獲取要上傳的文件對象(能夠上傳多個) // alert(upfile.name) //alert(upfile.type) var formdata = new FormData(); var xhr = new XMLHttpRequest(); formdata.append('upfile', upfile); //設置服務器端接收的name爲upfile xhr.open("post",""); xhr.onreadystatechange = function(){ if(this.readyState==4){ if(this.status==200){ //上傳成功 var resultText = this.responseText; console.info(resultText); //轉json var jsonObj = JSON.parse(resultText); console.info(jsonObj); if(jsonObj.success){ //var oUl = document.getElementById('ul1'); //var oLi = document.createElement('li'); //var oSpan = document.createElement('span'); //oSpan.innerHTML = jsonObj.res +" 剛纔上傳"; //oLi.appendChild(oSpan); //oUl.insertBefore(oLi, oUl.children[0]); //刷新 window.location.reload(); } }else{ alert('上傳失敗,請使用另外一種方式上傳'); } } } xhr.send(formdata); } } function upload(e){ var upfile = e.files[0]; var formdata = new FormData(); var xhr = new XMLHttpRequest(); formdata.append('upfile', upfile); //設置服務器端接收的name爲upfile xhr.open("post",""); xhr.onreadystatechange = function(){ if(this.readyState==4){ if(this.status==200){ //上傳成功 var resultText = this.responseText; //轉json var jsonObj = JSON.parse(resultText); console.info(jsonObj); if(jsonObj.success){ //刷新 window.location.reload(); } } } } xhr.send(formdata); } </script> <div><a href="/share">返回總目錄</a> - 本目錄文件</div> <ul id="ul1" > {{range $i, $v := .Files}} <li style="line-height:200%"> <span> {{$v.Name}} </span> <span> {{$v.Date}} </span> {{if $.FlagAllowDel}} <span> <a href='#' onclick="del({{$v.Url}})" >刪除</a> </span> {{else}} <span> <a href={{$v.Url}} download={{$v.Name}}>下載</a> </span> {{end}} </li> {{end}} </ul> <script type="text/javascript"> function del(path){ //alert(path); var formdata = new FormData(); var xhr = new XMLHttpRequest(); formdata.append('path', path); //設置服務器端接收 xhr.open("post",""); xhr.onreadystatechange = function(){ if(this.readyState==4){ if(this.status==200){ //成功 window.location.reload(); } }else{ //alert('刪除失敗'); } } xhr.send(formdata); } </script> </body> </html>
參考:https://blog.csdn.net/fyxichen/article/details/60570484app