Gin-Go学习笔记五:Gin-Web框架 文件的操作

文件的操作

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="100%;height:50px;">
        <button onclick="createtxt()" class="btn btn-primary">创建text文件</button>
        <label id="txtname"></label>
     </div>
      <!--写入文件-->
      <div style="100%;height:300px;margin-top:20px;">
          <label>输入内容:</label>
          <textarea id="writeinfo" style="50%;height:200px;" class="form-control"></textarea>
          <button value="写入内容" onclick="txtwrite()" class="btn btn-primary" style="margin-top:20px;">写入内容</button>
      </div>
     
      <!--读取文件内容部分-->
      <div style="100%;height:300px;">
          <button value="读取内容" onclick="txtread()" class="btn btn-primary" style="margin-bottom:20px;">读取内容</button>            
          <textarea id="readinfo" style="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接口的编写

原文地址:https://www.cnblogs.com/tudaogaoyang/p/8079093.html