1.此方法保存在BaseAction中,其他Action类中的方法直接调用即可
/**
* 保存上传的文件,使用UUID作为文件名,并返回为文件存储的全路径
*
* @param upload
* @return
*/
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
public String saveUploadFile(File upload) {
// 1.保存上传的文件,得到路径
String basePath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload_files/");// 返回的结果最后没有“/”
String subPath = sdf.format(new Date());
// String path = basePath + "/"+uploadFileName;
// 使用UUID作为文件名,以解决重名的问题
String path = basePath + subPath + UUID.randomUUID().toString();
// 如果文件夹不存在,就创建
File dir = new File(basePath + subPath);
if (!dir.exists()) {
dir.mkdirs();
}
File destFile = new File(path);
upload.renameTo(destFile);// 移动到目的地
return path;
}
2.在对应的数据库表中,应设置path属性(字段),用于保存文件保存的路径
//1,保存上传的文件,得到路径
String path = saveUploadFile(upload);
//2,创建新对象,并设置属性(也可以使用model)
model.setPath(path);
3./**
* 下载
* @return
* @throws Exception
*/
public String download() throws Exception
{
Message message = messageService.getById(model.getId());
inputStream = new FileInputStream(message.getPath());
// 解决下载的默认文件名中的中文乱码的问题
String fileName = URLEncoder.encode(message.getTitle(), "utf-8");
ActionContext.getContext().put("fileName", fileName);
return "download";
}
4.struts.xml配置下载的result
inputStream
application/octet-stream
attachment;filename="${#fileName}.doc"
注:action中应加上
private File upload;// 上传的文件
private String uploadFileName;// 上传的文件的名称
private InputStream inputStream;// 下载用的
private String uploadFileName;// 上传的文件的名称
private InputStream inputStream;// 下载用的
ps:不要忘了getter、setter方法哦