原生ajax+原生js上传下载文件

不用说话,直接看代码,直接copy也行

<!doctype html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .upload {
      width: 100px;
      height: 100px;
      display: flex;
      border: 1px dotted silver;
      border-radius: 50%;
      justify-content: center;
      align-items: center;
      color: white;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
      cursor:pointer;
    }
    .upload:active {
      color: black;
      background-color: skyblue;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
      cursor: auto;
    }
    .skyblue{
      background-color: skyblue;
    }
    .pink{
      background-color: pink;
    }
  </style>
</head>
<body>
<label class="upload skyblue" for="file">
  选择文件
  <input id="file" type="file" multiple style="display: none">
</label>
<br>
<div class="upload pink">
  上传文件
</div>
<br>
<input id="path" type="text">
<button onclick="getBlob()">下载</button>

<script>
  document.querySelector('#file').addEventListener('change', e => {
    upload(e.target.files)
  })
  function upload(files) {
    /* 这里演示的是多个上传,单个就自己改啦(或者不改都行,叫后端改啦) */
    const formData=new FormData()
    for (let i = 0; i < files.length; i++) {
      /* 文件名前加上时间戳 */
      formData.append('file',files[i],Date.now()+files[i].name)
    }
    const xhr=new XMLHttpRequest()
    xhr.open('POST','http://localhost:3000/user/upload')
    xhr.send(formData)
    xhr.onload=()=>{
      console.log('res:',xhr.response)
    }
  }
  function getBlob() {
    const xhr=new XMLHttpRequest()
    const url=document.querySelector('#path').value
    xhr.open('GET',url)
    xhr.send()
    /* 告诉服务器给我们返回的数据类型 */
    xhr.responseType='blob'
    xhr.onload=()=>{
      console.log('res:',xhr.response)
      downlaod(xhr.response)
    }
  }
  function downlaod(res) {
    /* res是响应,原生ajax请求,blob数据就是res,如果使用axios之类的外面有一层的data中(大概),下面这句就该是const blob=new Blob([res.data])*/
    const blob=new Blob([res])
    const a=document.createElement('a')
    a.style.display='none'
    a.download='图片下载.png'
    a.href=URL.createObjectURL(blob)
    document.body.appendChild(a)
    a.click()
    URL.revokeObjectURL(a.href); // 释放URL 对象
    document.body.removeChild(a);
  }
</script>
</body>
</html>


版权声明:本文为qq_42031498原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。