golang实现图片上传和下载

     golang实现图片上传和下载,测试过可行。filename传对应图片的名字,图片内容传二进制,其键为uploadfile。

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	//"os"
	//"strconv"
)

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		//fmt.Println(method)
		c.Header("Access-Control-Allow-Origin", "*")
		//c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, X_Tk, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		// 放行所有OPTIONS方法,因为有的模板是要请求两次的
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}

func main() {
	gin.SetMode(gin.DebugMode)
	router := gin.Default()
	router.Use(cors())
	router.POST("/uploadHandler",UploadHandler)
	router.GET("/fileDownload", FileDownload)
	router.Run(":10086")
}

//单张图片上传
func UploadHandler(c *gin.Context) {
	file, _ := c.FormFile("uploadfile")
	name := c.PostForm("filename")

	if len([]byte(name)) == 0{
		c.JSON(400,gin.H{"code":  400, "desc":  "not have filename"})
	}

	if file !=nil {
		if err := c.SaveUploadedFile(file, "./"+name); err != nil {
			c.JSON(500,gin.H{"code":  500, "desc":  "save file error"})
			return
		}
	}else{
		c.JSON(400,gin.H{"code":  400, "desc":  "not have uploadfile"})
	}

	c.JSON(200,gin.H{"code":  200, "desc":  "upload success"})
}


func FileDownload(c *gin.Context) {
	filename, err := c.GetQuery("filename")
	if !err {
		c.String(400, "Success")
	}

	path := "./"
	path += filename
	fmt.Println(path)
	c.File(path)
}

 

你可能感兴趣的:(golang)