服务端代码

  1. @GetMapping("/export")
  2. public void exportFile(MarkText markText, HttpServletResponse response) throws UnsupportedEncodingException {
  3. if (StringUtils.isBlank(markText.getFileName())) {
  4. return;
  5. }
  6. List<MarkText> list = markTextService.exportFile(markText);
  7. /**
  8. * 导出
  9. */
  10. response.setContentType("text/plain");
  11. String fileName = markText.getFileName();
  12. response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
  13. BufferedOutputStream buff = null;
  14. StringBuffer write = new StringBuffer();
  15. String enter = "\r\n";
  16. ServletOutputStream outSTr = null;
  17. try {
  18. outSTr = response.getOutputStream();
  19. buff = new BufferedOutputStream(outSTr);
  20. // 把内容写入文件
  21. if (list.size() > 0) {
  22. for (int i = 0; i < list.size(); i++) {
  23. MarkText text = list.get(i);
  24. write.append(text.getOrginText() + "," + text.getLabeledText() + "," + text.getSequencedText());
  25. write.append(enter);
  26. }
  27. }
  28. buff.write(write.toString().getBytes("UTF-8"));
  29. buff.flush();
  30. buff.close();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. } finally {
  34. try {
  35. buff.close();
  36. outSTr.close();
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }

浏览器代码

  1. exportFile(fileName) {
  2. const url = '/mark/export?fileName=' + fileName
  3. const a = document.createElement('a')
  4. a.download = 'test'
  5. a.href = url
  6. a.click()
  7. }