vue文件上传

vue文件上传



单文件上传

前端部分:

<template>
    <br>
  <a-from label="上传文件">
      <a-input type="file"></a-input>
      <a-button @click="upload" type="danger">上传</a-button>
  </a-from>
</template>
<script>
export default {
  data() {
    return {
      headers: {
        authorization: 'authorization-text',
      },
    };
  },
  methods: {
      upload() {
          const formData = new FormData();
          formData.append("file",document.querySelector('input[type=file]').files[0])
          // 因为不是以json的形式提交,所以无需使用qs转换
          this.$axios.post('/postfile',formData).then(function (response) {
                    console.log(response);
                }).catch(function (error) {
                    console.log(error);
            });
      }
  },
};
</script>

后端:

func PostFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message" : err.Error(),
		})
		return
	}
	log.Println(file.Filename)
	dst := fmt.Sprintf("uploadfile\\%s", file.Filename)
	c.SaveUploadedFile(file, dst)
	c.JSON(http.StatusOK, gin.H{
		"message" : fmt.Sprintf("'%s' uploaded!", file.Filename),
	})
}

多文件上传

前端:

<template>
  <br />
  <a-from label="多文件上传">
     <a-upload > </a-upload> 
    <input type="file" class="files" multiple="multiple">
    <a-button @click="upload" type="danger">上传</a-button>
  </a-from>
</template>
<script>
export default {
  data() {
    return {
      headers: {
        authorization: "authorization-text",
      },
    };
  },
  methods: {
    upload() {
      const formData = new FormData();
      const file = document.getElementsByClassName("files")[0].files;
      // console.log("上传的文件数量:" + file.length);
      for (let i = 0; i < file.length; i++) {
        formData.append("file", file[i]);
      }
      this.$axios
        .post("/postfiles", formData)
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>

后端:

func PostFiles(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["file"]

	for _, file := range files {
		log.Println(file.Filename)
		dst := fmt.Sprintf("uploadfile\\%s", file.Filename)
		c.SaveUploadedFile(file, dst)
	}
	c.JSON(http.StatusOK, gin.H{
		"message" : fmt.Sprintf("%d files uploaded!", len(files)),
	})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值