栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

struts2实现文件下载功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

struts2实现文件下载功能

本文实例为大家分享了struts2下实现文件下载功能,供大家参考,具体内容如下

下面以实现一个图片下载功能为例:

1. 项目结构

2. web.xml

 
 
 
  
  
  struts 2 
  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 
  
  
  struts 2 
  /* 
  
 
 
  
  
  index.jsp 
  
 
  
  
  30 
  
 
 

3.DownloadAction.java

package com.action; 
 
import java.io.InputStream; 
import org.apache.struts2.ServletActionContext; 
import com.opensymphony.xwork2.ActionSupport; 
 
public class DownloadAction extends ActionSupport{ 
 private static final long serialVersionUID = 1L; 
 //文件路径 
 private String path; 
  
 //path属性的getter方法 
 public String getPath(){ 
  return path; 
 } 
 //path属性的setter方法 
 public void setPath(String path){ 
  this.path = path; 
 } 
 //返回inputstream,文件下载关键方法 
 public java.io.InputStream getDownloadFile() throws Exception{ 
  InputStream in = ServletActionContext.getServletContext().getResourceAsStream(getPath()); 
  return in; 
 } 
 public String execute() throws Exception{ 
  return SUCCESS; 
 } 
} 

4.struts.xml

 
 
 
   
   
    
    
  
  
   
   
    
     
     
     
     
      
     image/jpeg 
      
      
       
 
      attachment;filename="a.jpg"   
      
      
       
     downloadFile 
      
     1024 
     
    
   

5.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
 
 
 
  
  
 首页 
  
  
 
欢迎来到首页,点下面链接去下载一个文件
">下载

  6.文件路径

项目中要提前建立好download目录,和里面要存在有a.jpg文件,否则,下载会失败。

7.功能入口

项目发布到服务器后,用浏览器访问项目中的index.jsp ,点击下载链接,就可以弹出“下载”对话框。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号