上传下载固定配置

上传页面主要文件:<s:form>表单,固定格式

<s:form action="upload" method="post" enctype="multipart/form-data" namespace="/">
            <s:file name="image"></s:file>
            <s:submit value="上传"></s:submit>
        </s:form>

struts配置        

<action name="upload" class="com.bawie.action.Upload" >
                <result name="success">
                /upload_success.jsp
            </result>
        </action>

<action name="download" class="com.bawie.action.Download">
            <param name="imgname">/img/</param>
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;filename="${filename}"</param>
                <!-- inputName对应数据必须是提供字节输入流的方法名去掉get后剩余部分首字母小写 -->
                <param name="inputName">download</param>
            </result>
        </action>     

类里的配置

public class Upload extends ActionSupport{

//2个属性,第一个是File类型,属性名必须与jsp页面name值同
    private File image;

//第二个属性必须是第一个属性名字+FileName;
    private String imageFileName;
    private String imageContentType;
  //提供省略get()和set()方法,这里省略
  public String execute() throws Exception{
       FileInputStream fis=new FileInputStream(image);

//获取项目根目录中img文件夹在硬盘中的绝对路径
        String realPath = ServletActionContext.getServletContext().getRealPath("img");
        String filename=realPath+File.separator+imageFileName;
        FileOutputStream fos=new FileOutputStream(filename);
        byte[] by=new byte[1024];
        int len=0;
        while((len=fis.read(by))!=-1){
            fos.write(by, 0, len);
        }
        fis.close();
        fos.close();
        return "success";      
    }

public class Download extends ActionSupport{
    private String imgname;
    private String filename;

// 省略get和set方法

//方法名必须以get开头

public InputStream getDownload(){
        return ServletActionContext.getServletContext().getResourceAsStream(imgname+filename);      
    }   
}

原文地址:https://www.cnblogs.com/hmpcly/p/7085332.html