首先我们可以定义一个具体类,命名为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>