文件上传&下载

这篇博客介绍了JavaScript中如何实现文件的上传和下载功能。通过创建输入元素触发文件选择,使用fetch API进行POST请求上传文件,并处理响应。对于文件下载,采用fetch获取blob数据,根据浏览器特性实现文件保存。
摘要由CSDN通过智能技术生成
  1. 文件上传
// js调用
var input = document.createElement('input')
input.id = 'template-upload'
 input.type = 'file'
 input.click()
 input.onchange = () => {
   var file = input.files[0]
   var form = new FormData()
   form.append('file', file) // 第一个参数是后台读取的请求key值
   // form.append('fileName', file.name)
   templateUpload(form).then(res => {
     this.$message.success(res)
   }).catch(error => {
     this.$message.error(error)
   })
 }

// 接口
export const templateUpload = (data) => {
  return fetch({
    url: '',
    method: 'post',
    data
  })
}
  1. 文件下载
// js调用
templateDownLoad().then(res => {
   const fileName = 'xxx.xlsx'
   const blob = new Blob([res], {
     type: 'application/vnd.ms-excel;charset=utf-8'
   })
   if (navigator.msSaveBlob) {
     navigator.msSaveBlob(blob, fileName)
   } else {
     const link = document.createElement('a')
     link.href = URL.createObjectURL(blob)
     link.download = fileName
     link.click()
     URL.revokeObjectURL(link.href)
   }
 })

// 接口
export const templateDownLoad = () => {
  return fetch({
    url: '',
    method: 'get',
    responseType: 'blob'
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wombat-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值