文件的操作
1> 文件的創建,刪除,寫入內容,讀取內容.(此實例使用的是text文件)
2> Gin 並沒有提供文件的創建,刪除,讀寫這個操作的專門的接口,所以采用的是常用的ioutil這個包進行文件的讀寫操作,使用os這個包進行文件的創建和刪除
3> 在controller下面新建一個fileopt.go,作為實現文件操作的業務邏輯部分.具體代碼如下:
package controllers import ( "io/ioutil" "fmt" "os" "github.com/gin-gonic/gin" "net/http" ) /**文件讀寫創建刪除操作頁面**/ func Filerwhtml(c *gin.Context){ c.HTML(http.StatusOK, "filerw.html", gin.H{ "title": "GIN: 文件讀寫創建刪除操作布局頁面", }) } /**創建文件**/ func FilerCreate(c *gin.Context){ iscreate:=true //創建文件是否成功 //創建文件 f, err:= os.Create("static/txtfile/log.text") if err!=nil{ iscreate=false } defer f.Close() fmt.Println(f) //返回結果 c.JSON(http.StatusOK, gin.H{ "path":"static/txtfile/log.text", "success":iscreate, }) } /**將內容寫入文件**/ func FilerWrite(c *gin.Context){ iswrite:=true //寫入文件是否成功 //需要寫入到文件的內容 info:=c.PostForm("info") path:=c.PostForm("path") d1 := []byte(info) err := ioutil.WriteFile(path, d1, 0644) if err!=nil{ iswrite=false } //返回結果 c.JSON(http.StatusOK, gin.H{ "success":iswrite, "info":info, }) } /**讀取文件內容**/ func FilerRead(c *gin.Context){ isread:=true //讀取文件是否成功 path:=c.PostForm("path") //文件讀取任務是將文件內容讀取到內存中。 info, err := ioutil.ReadFile(path) if err!=nil{ fmt.Println(err) isread=false } fmt.Println(info) result:=string(info) //返回結果 c.JSON(http.StatusOK, gin.H{ "content":result, "success":isread, }) } /**刪除文件**/ func FilerDelete(c *gin.Context){ isremove:=false //刪除文件是否成功 path :=c.PostForm("path") //源文件路徑 //刪除文件 cuowu := os.Remove(path) if cuowu != nil { //如果刪除失敗則輸出 file remove Error! fmt.Println("file remove Error!") //輸出錯誤詳細信息 fmt.Printf("%s", cuowu) } else { //如果刪除成功則輸出 file remove OK! fmt.Print("file remove OK!") isremove=true } //返回結果 c.JSON(http.StatusOK, gin.H{ "success":isremove, }) }
4> 在views下面新建一個fileopt.html作為頁面展示效果
<!DOCTYPE html> <html> <head> <title>{{.title}}</title> <link rel="shortcut icon" href="/static/img/favicon.png" /> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/> <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <!--創建text文件--> <div style="width:100%;height:50px;"> <button onclick="createtxt()" class="btn btn-primary">創建text文件</button> <label id="txtname"></label> </div> <!--寫入文件--> <div style="width:100%;height:300px;margin-top:20px;"> <label>輸入內容:</label> <textarea id="writeinfo" style="width:50%;height:200px;" class="form-control"></textarea> <button value="寫入內容" onclick="txtwrite()" class="btn btn-primary" style="margin-top:20px;">寫入內容</button> </div> <!--讀取文件內容部分--> <div style="width:100%;height:300px;"> <button value="讀取內容" onclick="txtread()" class="btn btn-primary" style="margin-bottom:20px;">讀取內容</button> <textarea id="readinfo" style="width:50%;height:200px;" class="form-control" ></textarea> </div> <button onclick="deletetxt()" class="btn btn-primary">刪除text文件</button> </div> <!--JS部分--> <script type="text/javascript"> //創建text文件 function createtxt(){ $.ajax({ type:'post', url:'/home/addfile', data:{}, success:function(result){ console.log('創建的結果') console.log(result) if(result.success){ $("#txtname").html(result.path); }else{ $("#txtname").html("新增失敗"); } } }) } //寫入文件的內容 function txtwrite(){ $.ajax({ type:'post', url:'/home/writefile', data:{ "info":$("#writeinfo").val(), "path":$("#txtname").html() }, success:function(result){ console.log('寫入的結果') console.log(result) if(result.success){ alert("寫入成功") $("#showinfo").html(result.info); }else{ alert("寫入內容失敗"); } } }) } //讀取文件的內容 function txtread(){ $.ajax({ type:'post', url:'/home/readfile', data:{ "path":$("#txtname").html() }, success:function(result){ console.log('讀取的結果') console.log(result) if(result.success){ $("#readinfo").html(result.content); }else{ alert("讀取內容失敗"); } } }) } //刪除text文件 function deletetxt(){ $.ajax({ type:'post', url:'/home/deletefile', data:{ "path":$("#txtname").html() }, success:function(result){ console.log('刪除的結果') console.log(result) if(result.success){ $("#txtname").html(''); alert("刪除成功"); }else{ alert("刪除失敗"); } } }) } </script> </body> </html>
5> 在router.go路由器中添加文件操作的路由
package routers import ( "github.com/gin-gonic/gin" . "GinLearn/GinLearn/apis" //api部分 . "GinLearn/GinLearn/controllers" //constroller部分 ) func InitRouter() *gin.Engine{ router := gin.Default() //Hello World router.GET("/", IndexApi) //渲染html頁面 router.LoadHTMLGlob("views/*") router.GET("/home/index", ShowHtmlPage) //列表頁面 router.GET("/home/list", ListHtml) router.POST("/home/PageData", GetDataList) router.POST("/home/PageNextData", PageNextData) //新增頁面 router.GET("/home/add", AddHtml) router.POST("/home/saveadd", AddPersonApi) //編輯頁面 router.GET("/home/edit", EditHtml) router.POST("/home/saveedit", EditPersonApi) //刪除 router.POST("/home/delete", DeletePersonApi) //Bootstrap布局頁面 router.GET("/home/bootstrap", Bootstraphtml) //文件的上傳和下載 router.GET("/home/fileopt", Fileopthtml) router.POST("/home/fileuplaod", Fileupload) router.GET("/home/filedown", Filedown) //文件的創建刪除和讀寫 router.GET("/home/filerw", Filerwhtml) router.POST("/home/addfile", FilerCreate)//創建文件 router.POST("/home/writefile", FilerWrite)//寫入文件 router.POST("/home/readfile", FilerRead)//讀取文件 router.POST("/home/deletefile", FilerDelete)//刪除文件 return router }
6> 使用到的項目結構如下:
7> 編譯運行代碼,測試執行的效果如下
8> 下一章講Api接口的編寫