原生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>
相关推荐
人工智能训练师1 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 天前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy1 天前
css的基本知识
前端·css
昔人'1 天前
css `lh`单位
前端·css
前端君1 天前
实现最大异步并发执行队列
javascript
破无差1 天前
《赛事报名系统小程序》
小程序·html·uniapp
Nan_Shu_6141 天前
Web前端面试题(2)
前端
知识分享小能手1 天前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队1 天前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光1 天前
css之一个元素可以同时应用多个动画效果
前端·css