java web下载word乱码
1.java代码
@PostMapping(value ="downloadWord")
@ApiOperation(value ="下载word")
private void downloadWord(HttpServletRequest request, HttpServletResponse response)throws IOException {
Word07Writer finalWriter =new Word07Writer();
OutputStream ouputStream = response.getOutputStream();
String paper_name ="paper_name";
response.reset();
// response.setContentType("application/octet-stream");
response.setContentType("application/msword");
response.addHeader("Content-Disposition", "attachment; filename=\"" +"test" +".docx\"");
response.setHeader("Accept-ranges", "bytes");
try {
String[] arrstrs =new String[]{"一", "二", "三", "四", "五", "六", "七", "八"};
AtomicInteger dnum =new AtomicInteger(0);//大题title
AtomicInteger num =new AtomicInteger(1);//小题title
Set strings =new HashSet<>();
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
finalWriter.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.PLAIN, 20), paper_name);
// finalWriter.flush(FileUtil.file("D:/" + title + ".docx"));
finalWriter.flush(ouputStream);
}finally {
ouputStream.close();
finalWriter.close();
}
}
2.web端代码
let url_post ='';
//post方式,param为所需要传的参数,
// responseType: 'arraybuffer'一定要写,否则下载的文件会出现乱码
axios.post(url_post, {}, {responseType:'arraybuffer' },{
headers: {
'Authorization':'Bearer ' +'23cdcd34-726f-4a22-84ea-a3ec9c7a3813',
}
})
.then(res => {
let blob =new Blob([res.data], {type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}); //type为所需要下载的文件格式,以xls文件为例
//浏览器兼容,Google和火狐支持a标签的download,IE不支持
if (window.navigator &&window.navigator.msSaveBlob) {
//IE浏览器、微软浏览器
/* 经过测试,微软浏览器Microsoft Edge下载文件时必须要重命名文件才可以打开 IE可不重命名,以防万一,所以都写上比较好*/
window.navigator.msSaveBlob(blob, '文件.docx');
}else {
//其他浏览器
let link =document.createElement('a'); // 创建a标签
link.style.display ='none';
let objectUrl =URL.createObjectURL(blob);
link.href = objectUrl;
link.click();
URL.revokeObjectURL(objectUrl);
}
})
.catch(err => {
this.$message.error(err.message);
});