后端代码:
public static
void genFile(HttpServletResponse response, Map map, String inputFileName, String outPutFileName) throws Exception {
String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
File inputFile=new File(staticPath+"/"+inputFileName);
XWPFTemplate template = XWPFTemplate.compile(inputFile).render(map);
String filePath = System.getProperty("java.io.tmpdir")+File.separatorChar+UUID.randomUUID().toString()+".docx";
template.writeToFile(filePath);
try {
File file = new File(filePath);
byte[] data = FileUtils.readFileToByteArray(file);
OutputStream output = response.getOutputStream();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.addHeader("Content-Length", String.valueOf(file.length()));
response.setContentType("application/octet-stream");
output.write(data);
output.flush();
output.close();
FileUtils.delete(file);
} catch (Exception e) {
e.printStackTrace();
}
}
前端代码:
npm install file-saver --save
import { saveAs } from 'file-saver';
import { downloadApi } from '@/api/factory'
methods: {
/** 提交按钮 */
submitForm() {
console.log("开始进行文件生成");
//this.downloadProgress = 10;
downloadApi(this.form, (e) => {
//this.downloadProgress = parseInt((e.loaded / e.total) * 100);
}).then(async (data) => {
const blob = new Blob([data]);
saveAs(blob, '11111.docx')
})
},
},
factory.js:
import http from '@/utils/http'
export function downloadApi(params, onDownloadProgress) {
return http.download('/api/test/tt', params, onDownloadProgress)
}
http.js:
import axios from 'axios'
import qs from 'qs'
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.timeout = 30 * 1000 // 30s request time out
let http = {}
http.axios = function (options) {
return new Promise((resolve, reject) => {
axios(options).then(res => {
resolve(res.data, res)
}).catch(err => {
reject(err)
})
})
}
http.post = function (url, params) {
return http.axios({
url: url,
method: 'post',
headers: {'Content-Type': 'application/json;charset=UTF-8', 'Content-Language': 'zh-cn'},
data: params
})
}
http.get = function (url, params) {
return http.axios({
url: url,
method: 'get',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: params
})
}
http.submit = function (url, params) {
return http.axios({
url: url,
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: qs.stringify(params)
})
}
http.upload = function (url, params) {
return http.axios({
url: url,
method: 'post',
headers: {'Content-Type': 'multipart/form-data'},
data: params
})
}
http.download = function (url, params, onDownloadProgress) {
return http.axios({
url: url,
method: 'post',
data: params,
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
responseType: 'blob',
onDownloadProgress: onDownloadProgress
})
}
export default http
最后
以上就是淡定鸭子最近收集整理的关于文件导出最佳实践(含前后端)的全部内容,更多相关文件导出最佳实践(含前后端)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复