栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Struts2实现文件下载功能代码分享(文件名中文转码)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Struts2实现文件下载功能代码分享(文件名中文转码)

struts2文件下载功能实现代码如下所示:

Action文件

public class DownLoadAction extends ActionSupport { 
 
private static final long serialVersionUID = 5879762231742395104L; 
private String fileName;//用户请求的文件名 
private String inputPath;//下载资源的路径(在struts配置文件中设置) 
public void setInputPath(String inputPath) { 
this.inputPath = inputPath; 
} 
public String getInputPath() { 
return inputPath; 
} 
public void setFileName(String fileName) { 
this.fileName = fileName; 
} 
public String getFileName() { 
return fileName; 
} 
public String downloadFile() throws Exception { 
ServletContext context = ServletActionContext.getServletContext(); 
String downloadDir = context.getRealPath("/upload"); 
String downloadFile = context.getRealPath(inputPath); 
//防止用户请求不安全的资源 
if(!downloadFile.startsWith(downloadDir)) { 
return null; 
} 
return "download_success"; 
} 
 
public InputStream getInputStream() throws Exception { 
String path = inputPath + File.separatorChar + new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); 
return ServletActionContext.getServletContext().getResourceAsStream(path); 
} 
 
public String getDownloadFileName() { 
String downloadFileName = fileName; 
try { 
downloadFileName = URLEncoder.encode(downloadFileName, "ISO-8859-1"); 
} catch (UnsupportedEncodingException e) { 
e.getMessage(); 
e.printStackTrace(); 
} 
return downloadFileName; 
} 
} 

jsp文件:

  • /download_DownLoadAction_downloadFile.action?fileName=dwr.jar">dwr.jar文件下在
  • /download_DownLoadAction_downloadFile.action?fileName=Struts2教程.pdf">Struts2教程.pdf文件下在
  • struts.xml:

     
    /upload 
     
     
     
    application/octet-stream 
     
    inputStream 
     
    attachment;filename="${downloadFileName}" 
     
    2048 
     
     

    以上所述是小编给大家介绍的Struts2实现文件下载功能代码分享(文件名中文转码)的相关内容,希望对大家有所帮助!

    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/149976.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号