Skip to content
本页目录

原始js文件上传

HTML

html
<div class="section-pushInChannel-fileInput">
  <!--  <input id="file" onChange="handleFileChange(event)" type="file" name="file" multiple="multiple"></input>-->
  <form enctype="multipart/form-data">
    <label for="file" class="filelabel el-button el-button--primary">上传简历</label>
    <input type="file"
           multiple
           ref="input_file"
           id="file"
           style="display: none"
           onChange="handleFileChange(event)"
    />
    <!--  accept="application/*"  :disabled="editPicList.length >= maxLength"-->
  </form>
<script type="text/javascript" src="./js/jquery.js"></script>
</div>

上传逻辑

javascript
// 类型校验
  function check(file) {
    //支持格式:doc .docx .pdf .xls .xlsx .csv  .ppt .pptx .txt .xmind .mmap .zip .jpeg .png
    const type = [
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/pdf',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'text/csv',
      'application/vnd.ms-powerpoint',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'text/plain',
      'application/x-zip-compressed',
      'application/zip',
      'application/x-zip',
      'image/jpeg',
      'image/png',
      'application/wps-office.doc',
      'application/wps-office.xlsx',
      'application/wps-office.docx',
      'application/wps-office.pptx',
      'application/wps-office.ppt',
      'application/wps-office.xls',
      'application/wps-office.xlsx'
    ]
    let checkType = type.includes(file.type)
    let checkSize = file.size > 1024 * 1024 * 50 //默认50MB
    if (!checkType) {
      alert('文件类型不合法,支持格式:doc .docx .pdf .xls .xlsx .csv  .ppt .pptx .txt .zip .jpeg .png')
      throw '文件类型不合法'
    }
    if (checkSize) {
      alert('文件大小超过限制')
      throw '文件大小超过限制'
    }
  }
  // 参数组装
  async function setOssParams(files) {
    let query = new FormData()
    query.append('file', files)
    return query
  }
 // 文件上传
  async function upload(query) {
    console.log(query)
    const headers = {
      'token': '',
      '请求头参数':''
    }
    $.ajax({
      url: 'http://xxxxxxxx/file/upload',
      type: 'POST',
      cache: false,
      data: query,
      headers,
      processData: false,
      contentType: false
    }).done(function(res, status) {
      if (res.code === 200) {
        alert(res.message)
      }
      console.log(res, status)
    }).fail(function(res) {
    })
  }
  // 主方法
  async function handleFileChange(e) {
    const files = e.target.files[0]
    try {
      await check(files)
      const query = await setOssParams(files)
      await upload(query)
    } catch (e) {
      console.log(e)
    }

  }