vue3+element-plus实现图片上传和下载,包含权限认证

3,419 阅读1分钟

单张图片上传

<template>
  <el-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("上传头像图片只能是 JPG 格式!");
      //   }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 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>

多图上传

<template>
  <el-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>

上传脚本

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资源文件下载
func DownloadFileService(c *gin.Context) {
	fileName := c.Param("name")
	//打开文件
	_, errByOpenFile := os.Open("./upload/" + fileName)
	//非空处理
	if errByOpenFile != nil {
		/*c.JSON(http.StatusOK, gin.H{
			"success": false,
			"message": "失败",
			"error":   "资源不存在",
		})*/
		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() {
	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))

	//公共图片目录
	router.Static("/upload", "./upload")
	router.GET("/yuemaedu", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"msg": "success", "code": 0})
	})
	// 根据流显示图片
	router.GET("/img/:name", func(c *gin.Context) {
		imageName := c.Param("name")
		file, _ := ioutil.ReadFile("./upload/" + imageName)
		c.Writer.WriteString(string(file))
	})
	//下载图片
	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()
	})

	// 上传单张图片
	router.POST("/upload", func(c *gin.Context) {
		//获取文件头
		file, err := c.FormFile("file")
		if err != 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})
	})
	// 上传多张图片
	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()
}