zoukankan      html  css  js  c++  java
  • 第三篇:图片上传 | <input/>样式不理想的解决方案 | FormData 对象

    前端上传图片的原理是:运用<input type=“file” />的标签获取图片信息(file),传给后台,完成上传。

    图片上传:

    需要页面展示图片的话,把图片信息放在<img />中

    <input type="file" onChange={() => { this.handleUpload(ev.target) }} />

    <input type=“file” />的样式不好设置,很难满足样式需求,网上提供几种解决办法,比较好的是设置样式 opcity = 0,使其定位覆盖在按钮之上。

    我在开发中觉得依旧不是很好,于是就有了下面的代码:

    uploadClick = async () => {
      const newFile = document.createElement("input");
      newFile.setAttribute("type", "file");
      newFile.addEventListener("change", () => {
        this.handleUpload(newFile)
      });
      await newFile.click();
      await newFile.remove();
    }
    handleUpload = (newFile) => {
      const fileData = newFile.files[0]; // 图片的信息
      console.log(fileData.name) // 图片的名称
    
      const reader = new FileReader();
      reader.readAsDataURL(fileData);
      reader.onload = function(ev) {
        console.log(ev)
        console.log(this.result) // 图片地址,可以直接给 img.src
      }
    
      const pettern = /^image/;
      if (!pettern.test(fileData.type)) { // 判断上传的文件是否是 图片
        fetch("http://xxxx.xxx", { // 发起请求
          method: "post",
          body: {
            "multipartFile": fileData
          },
          Headers: {
            "userToken": "xxxxxx", // 与后端商量好的请求头
            "......": "......"
          }
        }).then(res => {
          if (res.status !== 200) {
            console.log("上传失败", res)
          } else {
            console.log("上传成功", res)
          }
        })
      } else {
        alert("图片格式不正确")
      }
    }

    从上面的代码,我们能拿到图片的链接地址,和名称,渲染到页面上就完成了一次上传图片,并且显示

    参考文档:雪旭:https://www.cnblogs.com/zimengxiyu/p/11359053.html

    文件上传:

      同理,我们要先获取 文件,也就是 file,拿到内容之后,请求接口,将内容放在 body 中发送给后端。

      如果后端需要,FormData 类型的,就转一下,比如:

    const formdata = new FormData();
    formdata.append("xxx", file[0]); // xxx 是请求参数(和后端商量好的)

      将 formdata 复制给 接口的 body

  • 相关阅读:
    Git Cannot rebase: You have unstaged changes.
    importError: DLL load failed when import matplotlib.pyplot as plt
    install tushare in python 3.6
    pd.qcut, pd.cut, df.groupby()等在分组和聚合方面的应用
    从池子里的beta看秋香, 个性迥异
    个股和股票池的beta系数的估算
    检验两个随机序列的beta系数
    spyder里的"查找文件里的特定字符串"非常方便
    地图上道路编号中的G S X Y
    场内的代码表, 感觉水很深
  • 原文地址:https://www.cnblogs.com/MrZhujl/p/12726955.html
Copyright © 2011-2022 走看看