java jsp实现上传下载_jsp页面实现文件上传下载

新手初学,分享下经验,有不足的地方请多指点:

首先实现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() 关闭 否则会报错

提示框截图:

71a80c4c23de6f76129b05642e8405c4.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值