Struts2实现文件的上传和下载

JavaWeb开发中经常会遇到文件的上传和下载,其实我们可以有一套自己的方法,在任何地方直接拿来就可以使用,具体实现代码如下:
首先我们可以定义一个具体类,命名为Constant.java
public static final String UPLOADFILE_PATH = PropertyConfig.getProterties().getProperty("FILE_UPLOAD_DIR");
然后在config.properties文件中定义一个具体放置文件的目录
FILE_UPLOAD_DIR=uploadfiles
下面写具体的Java代码,实现上传功能

public String upload(){

//ngttfile 为后台jsp页面穿过来的文件,即<input type="file" name="ngttfile"/>,ngttfileFileName即可得到文件的名字,
在jsp页面中提交表单时记得加上enctype="multipart/form-data",否则是提交不了的

if(ngttfile !=null && !ngttfile.equals("")){
String listPath = Constants.UPLOADFILE_PATH;
   InWebPropertiesUtil util = new InWebPropertiesUtil("sysConfig/config.properties");
   String result = util.getIsCodeGetDomainName();
File listFile=new File(result+"/"+listPath);
   if(!listFile.exists()){
    listFile.mkdirs();
   }
   File newFile= new File(listFile+"/"+ngttfileFileName);
   try {
       if(!newFile.exists()){
        newFile.createNewFile();
       }
FileUtils.copyFile(ngttfile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
ngttResult.setReportName(ngttfileFileName);
ngttResult.setReportFilePath(newFile.toString());
}
//newFile.toString()即可得到存储文件的具体路径    

}

下面是下载方法

public String download(){

if (path != null && path.length() > 0) {
// path是指欲下载的文件的路径。
File file = new File(path);
String filename = file.getName();
if (file.exists()) {


// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(
new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ new String(filename.getBytes(),
"iso-8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} else {
String error = "文件“" + filename + "”不存在!";
String errorHtml = "<html>";
errorHtml = errorHtml + "<script>";
errorHtml = errorHtml + "function errorAlert(){";
errorHtml = errorHtml + "alert('" + error + "');";
errorHtml = errorHtml + "window.history.back();";
errorHtml = errorHtml + "}";
errorHtml = errorHtml + "</script>";
errorHtml = errorHtml + "<body οnlοad='errorAlert();'>";
errorHtml = errorHtml + "</body>";
errorHtml = errorHtml + "</html>";


response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(errorHtml);
}
}

}
在Struts2的配置文件里需要加上<result name="success" type="stream"></result>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值