Skip to content
原生html上传文件(隐藏file输入框)
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>html文件上传(隐藏输入框版本)</title>
  </head>
  <body>
    <button>点击上传文件</button>
    <input type="file" name="" id="" hidden />

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let btn = document.querySelector("button");
      let input = document.querySelector("input");

      btn.onclick = function() {
        input.click();
      };

      input.onchange = async function() {
        var file = input.files[0]; // 获取文件对象

        if (!file) {
          console.log("请选择图片");
          return;
        }
        if (!file.type.startsWith("image")) {
          console.log("只能上传图片");
          file = null;
          return;
        }

        console.log("file", file);

        var formData = new FormData();
        formData.append("file", file); // 添加文件到formData对象

        // 其它参数
        formData.append("venue_id", this.$route.params.venue_id);
        formData.append("type", "logo");
        formData.append("user_id", this.user_id);
        // formData本质就是一个大对象,如果使用了formData,就直接把formData对象传给后台即可,需要什么参数直接在formData对象中添加即可
        // 如果直接使用formData作为数据传的话,如{file:foreData,venue_id:this.$route.params.venue_id} 会导致后台接收不到venue_id,并且接收到的file也是空对象

        // 上传图片
        let res = await axios.post("/ptpro/Publicpush/uploadImage", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        console.log("res", res);
      };
    </script>
  </body>
</html>