Struts2 file download small Demo

1.LoginAction,java

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

public class downLoadAction {
    //读文件:io流 
    private InputStream is;
    private String fileName;
    public String execute() throws Exception{
        //读取服务器上的文件名
        fileName="1.jpg";
        //获取服务器路径
        is=ServletActionContext.getServletContext()
        .getResourceAsStream("/images/"+fileName);
        //重置文件名
        fileName="萌宠.jpg";
        //中文乱码
        fileName= new String(fileName.getBytes("utf-8"),"iso-8859-1");
        return "success";
    }


    public InputStream getIs() {
        return is;
    }
    public void setIs(InputStream is) {
        this.is = is;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

2.struts2.xml

<?xml version="1.0" encoding="UTF-8"?>

   <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="xxx" extends="struts-default">
        <action name="download" class="com.lanou3g.action.downLoadAction">
            <result type="stream">
                <!--附件格式下载 -->
                <param name="contentDisposition">attachment;filename=${fileName}
                </param>
                <param name="inputName">is</param>

            </result>

        </action>
    </package>

</struts>

3.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>

    <a href="download">下载</a>
  </body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325904083&siteId=291194637