原生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>
相关推荐
牛奶27 分钟前
如何自己写一个浏览器插件?
前端·chrome·浏览器
亿元程序员1 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY1 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技1 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3011 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
ZhengEnCi1 小时前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
文心快码BaiduComate1 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员
hunterandroid2 小时前
Compose 状态管理:remember、rememberSaveable 与状态提升
前端
星栈2 小时前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架
晴虹2 小时前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js