Single picture upload

< the template > < el - the upload class = "avatar - uploader" action = "http://127.0.0.1:8080/upload" : show - file - list = "false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{ Authorization: 'qq:976961880' }" > <img v-if="imageUrl" :src="imageUrl" class="avatar" /> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </template> <script> export default { data() { return { imageUrl: "", }; }, methods: { handleAvatarSuccess(res, file) { this.imageUrl = URL.createObjectURL(file.raw); }, beforeAvatarUpload(file) { // const isJPG = file.type === "image/jpeg"; const isLt2M = file.size / 1024 / 1024 < 2; // if (! IsJPG) {// this.$message.error(" Upload avatar image can only be JPG!" ); // } if (! IsLt2M) {this.$message.error(" Upload avatar image size can not exceed 2MB!" ); } // return isJPG && isLt2M; return isLt2M; ,}}}; </script> <style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409eff; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; line-height: 178px; text-align: center; } .avatar { width: 178px; height: 178px; display: block; } </style>Copy the code

Upload photos

< the template > < el - the upload action = "http://127.0.0.1:8080/upload" list - type = "picture - card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="{ Authorization: 'qq:976961880' }" > <i class="el-icon-plus"></i> </el-upload> <el-dialog v-model="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt="" /> </el-dialog> </template> <script> export default { data() { return { dialogImageUrl: "", dialogVisible: false, }; }, methods: { handleRemove(file, fileList) { console.log(file, fileList); }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; ,}}}; </script> <style> </style>Copy the code

Upload script

package main

import (
	"io/ioutil"
	"net/http"
	"os"

	"github.com/gin-contrib/cors"

	"github.com/gin-gonic/gin"
)

const SERVER = "http://127.0.0.1:8080"

//TODO Test resource file download
func DownloadFileService(c *gin.Context) {
	fileName := c.Param("name")
	// Open the file
	_, errByOpenFile := os.Open("./upload/" + fileName)
	// Non-null processing
	iferrByOpenFile ! =nil {
		/ * SAN Antonio SON (HTTP StatusOK, gin. H {" success ": false," message ":" failure ", "error" : "resource does not exist,"}) * /
		c.JSON(http.StatusBadRequest, gin.H{"msg": errByOpenFile.Error(), "code": 1})
		return
	}
	c.Header("Content-Type"."application/octet-stream")
	c.Header("Content-Disposition"."attachment; filename="+fileName)
	c.Header("Content-Transfer-Encoding"."binary")
	c.File("./upload/" + fileName)
}
func main(a) {
	router := gin.Default()
	defaultConfig := cors.DefaultConfig()
	defaultConfig.AllowAllOrigins = true
	defaultConfig.AllowMethods = []string{"GET"."POST"."PUT"."PATCH"."DELETE"."HEAD"."OPTIONS"}
	defaultConfig.AllowHeaders = []string{"Origin"."Content-Length"."Content-Type"."Authorization"}
	defaultConfig.ExposeHeaders = []string{"Content-Length"}
	router.Use(cors.New(defaultConfig))

	// Public image directory
	router.Static("/upload"."./upload")
	router.GET("/yuemaedu".func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"msg": "success"."code": 0})})// Display the image according to the stream
	router.GET("/img/:name".func(c *gin.Context) {
		imageName := c.Param("name")
		file, _ := ioutil.ReadFile("./upload/" + imageName)
		c.Writer.WriteString(string(file))
	})
	// Download the image
	router.GET("/downloadFiles/:name", DownloadFileService)

	router.Use(func(c *gin.Context) {
		if c.GetHeader("Authorization") != "qq:976961880" {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"msg": "auth failed"."code": 1})
			return
		}
		c.Next()
	})

	// Upload a single image
	router.POST("/upload".func(c *gin.Context) {
		// Get the file header
		file, err := c.FormFile("file")
		iferr ! =nil {
			c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error(), "code": 1})
			return
		}
		if _, err := os.Stat("./upload"); err ! =nil {
			if os.IsNotExist(err) {
				os.Mkdir("./upload".0777)
			}
		}
		fileName := file.Filename
		if err := c.SaveUploadedFile(file, "./upload/"+fileName); err ! =nil {
			c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error(), "code": 1})
			return
		}
		c.JSON(http.StatusOK, gin.H{"msg": "success"."data": SERVER + "/upload/" + fileName, "code": 0})})// Upload multiple images
	router.POST("/uploads".func(c *gin.Context) {
		form, _ := c.MultipartForm()
		files := form.File["file[]"]
		if _, err := os.Stat("./upload"); err ! =nil {
			if os.IsNotExist(err) {
				os.Mkdir("./upload".0777)
			}
		}
		imgList := []string{}
		for _, file := range files {
			fileName := file.Filename
			if err := c.SaveUploadedFile(file, "./upload/"+fileName); err ! =nil {
				c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error(), "code": 1})
				return
			} else {
				imgList = append(imgList, SERVER+"/upload/"+fileName)
			}
		}
		c.JSON(http.StatusOK, gin.H{"msg": "success"."data": imgList, "code": 0})
	})
	router.Run()
}

Copy the code