文件上传阿里云(使用Ant Design)

前端页面经常需要进行文件上传,那么就需要实现配合后端实现文件上传oss阿里云,下面区分了使用组件和不使用组件进行上传的情况

ant design的文件上传组件如下

<div v-show="addFile">
       <a-upload-dragger
            :customRequest="uploadFile"
            name="file"
            :multiple="true"
             @change="fileChange"
             accept=".pdf,.doc,.docx"
          >             
             <p class="ant-upload-drag-icon">
                  <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">
                    点击选择上传pdf文件
               </p>
               <p class="ant-upload-hint">
                     支持单个或批量上传
                </p>
          </a-upload-dragger>
 </div>

注意需要通过customRequest自定义上传方法
这里我定义了文件需要为pdf和word,如果你有别的需求可以更改accept属性

接下来是具体上传阿里云的代码

注意

  • getOss(file)方法是通过后端获取AccessKeyId等数据,当然也可以自己去官方获取
  • 如果你没有使用组件库,那么使用下面的方法就可以,如果使用了ant design需要看第三步
 ossLoad(file, ossData) {
        let fileName = file.name
        let fd = new FormData(),
          key = ossData.dir + uuid()
        fd.append('key', key)
        fd.append('success_action_status', '200')
        fd.append('x-oss-meta-fullname', fileName)
        fd.append('OSSAccessKeyId', ossData.accessKeyId)
        fd.append('policy', ossData.policy)
        fd.append('signature', ossData.signature)
        fd.append('file', file)
        // 数据组装完成后,发送上传请求到阿里云oss
        axios({
          url: ossData.host,
          method: 'POST',
          data: fd,
          processData: false,
          cache: false,
          contentType: false,
        })
        .then(res => {
            // 拿到结果后,做其他操作
          console.log(res);
            if (res.status == '200') {
            //如果没有使用ant design不写这一行
            this.$set(file,'status','done')
          }
        })
      },
      async getOss(file) {
        // 获取oss信息
        let res = await OssSend()
        if (res.code == 200) {
          this.ossLoad(file, res.data)
        }
      },

改变文件状态完成上传

  • uploadFile方法为上面定义的自定义上传操作,我写成空是因为我只是用它取消了默认发送的请求
  • 具体的上传方法我写在了fileChange方法中,以便判断状态
  • 这里我手动判断了状态,在状态为’uploading’时调用了getOss进行上传,并且在ossLoad方法中将上传成功后的状态改变了

     uploadFile() {},
     fileChange(info) {
     const status = info.file.status;
     if (status !== 'uploading') {
       console.log(info.file, info.fileList);
       } else {
    	 this.getOss(info.file)
     }
     if (status === 'done') {
       this.$message.success(`${info.file.name} file uploaded successfully.`);
     } else if (status === 'error') {
       this.$message.error(`${info.file.name} file upload failed.`);
      }
     
   },

需要注意的地方

  • 注意状态判断,如果请求完成不改变状态页面会一直显示文件上传状态
  • 如果你没有使用customRequest覆盖默认行为,那么会自动发送请求,所以如果你不使用默认的请求最好把它覆盖掉
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Ant Design 的 Upload 组件可以上传文件,并且可以通过一些配置来获取上传的文件数据。如果上传的文件是 Excel 文件,我们可以使用 js-xlsx 库来读取 Excel 数据。 下面是一个示例代码: ```vue <template> <div> <a-upload accept=".xls,.xlsx" :before-upload="beforeUpload" :on-success="onSuccess" > <a-button> <a-icon type="upload" /> 点击上传 </a-button> </a-upload> <div v-if="excelData"> <h3>Excel 数据</h3> <table> <thead> <tr> <th v-for="(value, key) in excelData[0]">{{ key }}</th> </tr> </thead> <tbody> <tr v-for="row in excelData"> <td v-for="value in row">{{ value }}</td> </tr> </tbody> </table> </div> </div> </template> <script> import XLSX from 'xlsx'; export default { data() { return { excelData: null, }; }, methods: { beforeUpload(file) { // 只处理 Excel 文件 const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; if (!isExcel) { this.$message.error('只能上传 Excel 文件!'); return false; } }, onSuccess(response) { // 读取 Excel 数据 const workbook = XLSX.read(response.file.response, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 第一行为表头,去掉 data.shift(); this.excelData = data; }, }, }; </script> ``` 在这个示例代码中,我们使用Ant Design 的 Upload 组件,并通过 `accept` 属性限制只能上传 Excel 文件。在上传之前,我们可以通过 `before-upload` 属性来判断是否是 Excel 文件,并在不是 Excel 文件的情况下给用户提示错误信息。 在上传成功后,我们可以通过 `on-success` 属性来获取上传的文件信息。`response.file.response` 是上传成功后服务器返回的文件内容,我们使用 js-xlsx 库来读取 Excel 数据,然后将数据显示在页面上。 需要注意的是,这里使用了 `XLSX.utils.sheet_to_json` 方法将 Excel 表格转换成 JSON 格式的数据,但是这个方法只能转换表格中有数据的部分,如果表格中有合并单元格等特殊情况,可能会出现转换错误的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值