前端代码实现文件下载功能及解决文件名称乱码问题
前端代码实现文件下载功能及解决文件名称乱码问题
1. 前端代码
function downloadFile(filenamerel, fileName) {
if ($('#sessionAccountName').val() != '') {
var currentTime = new Date();
if (($('#sessionVipType').val() != 0 & Date.parse(currentTime) < Date.parse($('#sessionVipExpiration').val())) || $('#sessionUserType').val() == 4) {
var $downForm = $('<form method='get'></form>');
$downForm.attr('action', '/laws/downloadEdiFile.html');
var $input = $('<input type='hidden'>');
$input.attr('name', 'fileSuccessUrl');
$input.val(filenamerel);
$downForm.append($input);
var $inputTwo = $('<input type='hidden'>');
$inputTwo.attr('name', 'fileSuccessName');
$inputTwo.val(fileName);
$downForm.append($inputTwo);
$(document.body).append($downForm);
// 提交表单,实现下载
$downForm.submit();
} else {
toastr.error('此功能仅VIP会员可用,请登录/续费!');
}
} else {
swal({
title: '操作提示', // 弹出框的title
text: '登陆后下载附件', // 弹出框里面的提示文本
type: 'warning', // 弹出框类型
showCancelButton: true, // 是否显示取消按钮
confirmButtonColor: '#DD6B55',// 确定按钮颜色
cancelButtonText: '取消',// 取消按钮文本
confirmButtonText: '确定',// 确定按钮上面的文档
closeOnConfirm: true,
}, function () {
$('#myModalLogin').css('top', '20%');
$('#myModalLogin').modal('show');
});
}
}
2. 后端代码
@RequestMapping(value = "/downloadEdiFile", method = RequestMethod.GET)
public void downloadEdiFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileUrl = request.getParameter("fileSuccessUrl");
String fileName = request.getParameter("fileSuccessName");
// 获取文件保存地址
String filePath = fileUrl;
// 读取文件
URL url = new URL(filePath);
URLConnection conn = url.openConnection();
InputStream txtIn = conn.getInputStream();
OutputStream os = response.getOutputStream();
String userAgent = request.getHeader("user-agent").toLowerCase();
try {
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 文件名转码
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setContentType("application/octet-stream; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);// @TODO 的文件名称
// 文件缓存区
byte[] bytes = new byte[1024];
// 判断输入流中的数据是否已经读完的标致
int len = 0;
while ((len = txtIn.read(bytes)) > 0) {
os.write(bytes, 0, len);
}
} catch (Exception e) {
logger.error("附件下载失败", e);
} finally {
if (os != null) {
os.close();
}
if (txtIn != null) {
txtIn.close();
}
// 增加下载记录
SysUser user = (SysUser) request.getSession().getAttribute("sysUser");
SysLaws laws = (SysLaws) request.getSession().getAttribute("laws");
if (Strings.isNullOrEmpty(request.getParameter("type")) && user.getUserType() != 4) {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 可以方便地修改日期格式
String time = dateFormat.format(now);
if (user != null) {
DownloadRecords downloadRecords = getFormMap(DownloadRecords.class);
downloadRecords.setDownloadpersonId(user.getId());
downloadRecords.setDownloadpersonName(user.getAccountName());
downloadRecords.setTitleId(laws.getId());
downloadRecords.setTitleName(laws.getLawsName());
downloadRecords.setDownloadUrl(fileUrl);
downloadRecords.setDownloadTime(time);
downloadRecords.setDownloadFilename(fileName);
downloadRecordsService.insertSelective(downloadRecords);
request.getSession().setAttribute("downloadRecords", downloadRecords);
}
}
}
}
3. 解决文件名称乱码的问题
文件名称乱码的原因是在后端代码中没有正确处理文件名称的编码问题。解决方法是使用正确的编码方式对文件名称进行编码。
在后端代码中,可以使用以下代码对文件名称进行编码:
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 文件名转码
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
将上述代码添加到设置响应头的代码之前,即可解决文件名称乱码的问题。
4. 总结
本文介绍了使用前端代码实现文件下载功能,并提供了解决文件名称乱码问题的代码示例。通过对文件名称进行编码,可以确保在不同浏览器下都能正确显示文件名称。
原文地址: https://www.cveoy.top/t/topic/qdqn 著作权归作者所有。请勿转载和采集!