服务端代码
@GetMapping("/export")
public void exportFile(MarkText markText, HttpServletResponse response) throws UnsupportedEncodingException {
if (StringUtils.isBlank(markText.getFileName())) {
return;
}
List<MarkText> list = markTextService.exportFile(markText);
/**
* 导出
*/
response.setContentType("text/plain");
String fileName = markText.getFileName();
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
outSTr = response.getOutputStream();
buff = new BufferedOutputStream(outSTr);
// 把内容写入文件
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
MarkText text = list.get(i);
write.append(text.getOrginText() + "," + text.getLabeledText() + "," + text.getSequencedText());
write.append(enter);
}
}
buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buff.close();
outSTr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
浏览器代码
exportFile(fileName) {
const url = '/mark/export?fileName=' + fileName
const a = document.createElement('a')
a.download = 'test'
a.href = url
a.click()
}