【文件导出】vue中使用post文件导出

一,前端利用form表单实现导出及下载文件

        后端给我的是一个post接口。我之前一直采用 a 标签来导出,导出的文件不是打不开,就是一个txt文件,我打出来后端返回的,才发现返回的data是一个二进制流(看起来像乱码一样)。所以就想到用表单来做,然后成功了。

        先设置一个通用的方法exportExcel

exportExcel (params, url) {
  const form = document.createElement('form')
  form.style.display = 'none'
  form.action = url
  form.method = 'post'
  document.body.appendChild(form)
  for (const key in params) {
    const input = document.createElement('input')
    input.type = 'hidden'
    input.name = key
    input.value = params[key]
    form.appendChild(input)
  }
  form.submit()
  form.remove()
}

        然后在页面使用

// 页面中直接用@click
<btn buttonname='导出' @click="exportHandle()" />

// 导出
exportHandle () {
    const params = {
        any: this.any
    }
    exportExcel(params, 'http://172.0.0.0:8080/Excel')
},

二,可能报错

         前端POST表单提交,后台服务报错 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported。

        此种情况为前端与后端json格式不统一导致。使用form时,默认是 application/x-www-form-urlencoded ,这里使用的参数接收注解是:@RequestParam 用来接收此类型的json参数正常。当前端定义为 application/json 时,这里使用的参数接收注解是:@RequestBody 可以正常接收json。

        所以你需要看后端使用的是什么 @RequestParam 还是其他,然后来确定自己的请求头。

// 导出excel
export function postExcelFile (params, url) {
  const form = document.createElement('form')
  form.style.display = 'none'
  form.enctype = 'application/json;charset=utf-8' // 向后端确定他的请求头
  form.action = url
  form.method = 'post'
  document.body.appendChild(form)
  for (const key in params) {
    const input = document.createElement('input')
    input.type = 'hidden'
    input.name = key
    input.value = params[key]
    form.appendChild(input)
  }
  form.submit()
  form.remove()
}

        如果你配合后端的参数接收注解不能解决你的问题,那么建议让后端修改参数注解为@RequestBody 或者 @ModelAttribute  。下面是其中一种写法供参考。

@PostMapping("infoExcel")
public void infoExcel(@ModelAttribute HrInfo info, HttpServletResponse response) throws Exception {
    List<HrInfo> hrInfos = getHrInfos(info);
    ExcelWriter writer = ExcelUtil.getWriter(true);
    writer.passCurrentRow();
    writerInfo(writer);
    geneExcel(response, hrInfos, writer);
}

猜你喜欢

转载自blog.csdn.net/pleasantsheep_/article/details/126419571