GIN框架文件上传之文件解压以及文件上传重复

GIN框架文件上传之文件解压以及文件(上传重复)

转go小半年,还是啥也不会,解决一个gin框架上传文件是解压,以及文件去重
望笑纳

func ProIdAdd( c *gin.Context ){
	var val modes.ProId
	jwt_user := modes.JwtUser(c)
	files, hand, err := c.Request.FormFile("file")
	// files, _, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON( http.StatusOK, gin.H{"err":1,"msg": err.Error()})
		return
	}
	//  file_name :=fmt.Sprintf("./upload/%s",hand.Filename)		// /home/shane/html/tg_index

	file_name :=fmt.Sprintf("/home/shane/html/tg_index/%s", hand.Filename )
	out,err := os.Create( file_name)
	if err != nil {
		c.JSON(http.StatusOK,gin.H{"err":2,"msg":err.Error()})
		return
	}
	if _,err := io.Copy(out,files);err !=nil {
		c.JSON(http.StatusOK,gin.H{"err":3,"msg":err.Error()})
		return
	}
	out.Seek(0,0)
	buf:= make([]byte,5242880)	//5242880
	out.Read(buf)
	val.Code = lib.StrMd5Str(string( buf ))	//MD5生成一个唯一的哈希值(不可逆)
	if fage, err := val.Get(); nil == err {
		if fage {
			c.JSON(http.StatusOK,gin.H{"err":4,"msg":"文件已经上传,请勿重复导入"})
			out.Close()
			os.Remove(file_name)
			return
		}
	}else{
		c.JSON(http.StatusOK,gin.H{"err":5,"msg":err.Error()})
		return
	}
	out.Close()
	val.CName =jwt_user.Name
	val.ChannelId ,_ = strconv.ParseInt(c.PostForm("channel_id"),10,64)
	val.MisoId ,_ = strconv.ParseInt(c.PostForm("miso_id"),10,64)
	val.Account	= c.PostForm("account")
	val.Methods ,_ = strconv.Atoi( c.PostForm("methods") )
	val.ProThe ,_ = strconv.Atoi( c.PostForm("prothe") )
	val.ProWay ,_ = strconv.Atoi( c.PostForm("proway") )
	url	:= c.PostForm("ursine")					//文件地址
	val.Urlone = c.PostForm("urlone")			//域名
	val.KeyFile = file_name
	val.Ursine	= fmt.Sprintf("%s/%s",val.Urlone,url)
	fmt.Println("--------hand.Filename---------",hand.Filename)
	urltwo  :=fmt.Sprintf(c.PostForm("ursine")+".zip")
	// fmt.Printf("--------url---------",urltwo)
	if urltwo != hand.Filename {
		c.JSON(http.StatusOK,gin.H{"err":6 , "msg":"上传文件名称与文件地址不不符"})
		return
	}
	if _, err = val.Save();nil != err {
		c.JSON(http.StatusOK,gin.H{"err":7 , "msg":err.Error()})
		return
	}
	// 解压 liunx脚本命令,当然东西还是要放到服务器上的
	command  :="unzip -q ~/html/tg_index/"+hand.Filename+" -d ~/html/tg_index/"
	fmt.Println(command)
	cmd := exec.Command("/bin/bash","-c",command)
	output,err := cmd.Output()
	if err != nil {
		fmt.Printf("Execute Shell:%s failed with error:%s", command, err.Error())
	}
	fmt.Printf("Execute Shell:%s finished with output:\n%s", command, string(output))

	c.JSON(http.StatusOK, gin.H{"err": 0,"msg": "ok"})
}

你可能感兴趣的:(golang,gin)