页面上传文件点击下载时文件名乱码的问题

注意将页面的编码转成iso-8859-1:

public void service(IRequestCycle cycle) throws UnsupportedEncodingException {
String filePath = cycle.getParameter("file");
File file = new File(filePath);
String filename = cycle.getParameter("filename");
String encode = cycle.getParameter("encode");
if (StringUtils.isEmpty(encode)) {
encode = "false";
}
String sfjm = cycle.getParameter("sfjm");
if (StringUtils.isEmpty(sfjm)) {
sfjm = "false";
}
if (filename == null || filename.equals("")) {
filename = file.getName();
} else {
if (encode.equalsIgnoreCase("true")&&sfjm.equalsIgnoreCase("true")) {
filename = Base64.decode_eps(filename);
filename = encodingFileName(filename);
log.info("=========download.svc==========Base64.decode_eps(filename)=" + filename);
} else if (encode.equalsIgnoreCase("utf8")&&sfjm.equalsIgnoreCase("true")) {
try {
filename = new String(filename.getBytes("UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
try {
if (System.getProperty("file.separator").equalsIgnoreCase("/")) {
filename = new String(filename.getBytes("gbk"), "iso-8859-1");
} else {
filename=new String(filename.getBytes("ISO-8859-1"), "utf-8");
filename = new String(filename.getBytes(), "ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
String type = cycle.getParameter("type");
if (type == null || type.equals("")) {
type = "application/x-msdownload";
}
OutputStream out = null;
FileInputStream in = null;
response.setContentType(type);

try {
if (file.exists() && file.getCanonicalPath().toLowerCase().replace("\\", "/").startsWith(Constants.FILEPATH.toLowerCase().replace("\\", "/"))) {
try {
out = response.getOutputStream();
if (type == null || !type.equalsIgnoreCase("text/html")) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
}
response.setContentLength(Long.valueOf(file.length()).intValue());
in = new java.io.FileInputStream(file);
if (in != null) {
byte[] buffer = new byte[1024 * 512];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
out.flush();
}
}

}catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
} else {
log.error("文件'" + filePath + "'不存在!");
}
} catch (IOException e) {
log.error("文件'" + filePath + "'不存在!");
e.printStackTrace();
}
}

posted @ 2019-06-20 16:28  凉生未央  阅读(516)  评论(0编辑  收藏  举报