新手初学,分享下经验,有不足的地方请多指点:
首先实现jsp页面上传附件:
页面文件关键代码
上传附件:Action代码
private File file;
private String fileFileName;
private String fileContentType;
注意命名方式:FileName 和 ContentType 前面要加对应的File名称
String savePath = "d:/project/"+this.fileFileName;
//savePath是保存的路径,上面的路径是我自己指定的
//一般是在WebContent下新建一个Folder“upload”
//用下面的方法获取到tomcat下工程部署的路径存储
//ServletActionContext.getServletContext().getRealPath("/upload/"+this.fileFileName);
FileInputStream fileInputStream=null;
FileOutputStream fileOutputStream=null;
try {
fileInputStream = new FileInputStream(file);
fileOutputStream=new FileOutputStream(savePath);
IOUtils.copy(fileInputStream, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
下面实现文件下载,并弹出提示框
文件:${email.attachment}
email!download 是一个action , 点击a标签后跳转到该action,获取文件的路径并跳转到download.jsp页面
download.jsp页面:
String fileName = (String)session.getAttribute("fileFileName");//文件名
String filePath = (String)session.getAttribute("saveAttachmentPath");//文件路径
//流操作
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream os = response.getOutputStream();
try {
FileInputStream fis = new FileInputStream(filePath);
try {
byte[] buffer = new byte[1024 * 10];
for (int read; (read = fis.read(buffer)) != -1;) {
os.write(buffer, 0, read);
}
} finally {
fis.close();
}
} finally {
out.clear();
out = pageContext.pushBody();
}
%>
这里要注意的是:output 要用 out.clear()及out=pageContext.pushBody() 关闭 否则会报错
提示框截图: