struts上传下载示例

来源:互联网 发布:mac 添加ttf字体 编辑:程序博客网 时间:2024/06/04 19:41

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts>    <constant value="message" name="struts.custom.i18n.resources"/>    <constant value="10000000" name="struts.multipart.maxSize"/>    <constant name="struts.multipart.saveDir" value="/tmp"/>    <package name="rentcar" namespace="/upload" extends="struts-default">        <interceptors>            <interceptor-stack name="fileStack">                <interceptor-ref name="defaultStack">                    <param name="fileUpload.maximumSize">2097152</param>                    <!-- <param name="fileUpload.allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param> -->                </interceptor-ref>            </interceptor-stack>        </interceptors>        <action name="uploadAction" class="com.hp.easycar.action.UploadAction">            <interceptor-ref name="defaultStack">                <param name="fileUpload.maximumSize">1000000</param>                <param name="fileUpload.allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>            </interceptor-ref>            <param name="savePath">/upload</param>            <result name="input">/upload/upload.jsp</result>            <result name="success">/upload/success.jsp</result>        </action>        <action name="multipleUploadAction" class="com.hp.easycar.action.MultipleUploadAction">            <interceptor-ref name="fileStack" />            <param name="savePath">/upload</param>            <result name="input">/upload/multipleUpload.jsp</result>            <result name="success">/upload/multipleSuccess.jsp</result>        </action>    </package>    <package name="rentcar1" namespace="/downSpace" extends="struts-default">        <action name="downloadAction" class="com.hp.easycar.action.DownloadAction">            <result name="success" type="stream">                <param name="contentType">${contentType}</param>                <param name="contentDisposition">attachment;filename="${downFileName}"</param>                <param name="inputName">downloadFile</param>                <param name="bufferSize">4096</param>            </result>        </action>        <action name="downloadAction2" class="com.hp.easycar.action.DownloadAction2">            <result type="stream">                <param name="bufferSize">2048</param>            </result>        </action>    </package></struts>

upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib uri="/struts-tags" prefix="s" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>文件上传</title>    <meta content="text/html; charset=utf-8" http-equiv=Content-Type>  </head>  <body>    <s:fielderror />    <form action="uploadAction" method="post" enctype="multipart/form-data">        文件标题:<input type="text" name="myFileTitle" /><br />        选择文件:<input type="file" name="myFile" /><br />        <input value="上传" type="submit" />    </form>  </body></html>

UploadAction.java

package com.hp.easycar.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.UUID;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {    private static final long serialVersionUID = 1L;    // myFileTitle属性用于封装文件标题    private String myFileTitle;    // myFile属性用于封装上传的文件    private File myFile;    // myFileContentType属性用于封装上传文件的类型    private String myFileContentType;    // myFileName属性用于封装上传的文件名    private String myFileFileName;    // savePath属性用于封装上传的保存路径    private String savePath;    public void setMyFileTitle(String myFileTitle) {        this.myFileTitle = myFileTitle;    }    public String getMyFileTitle() {        return this.myFileTitle;    }    public void setMyFile(File myFile) {        this.myFile = myFile;    }    public File getMyFile() {        return this.myFile;    }    public void setMyFileContentType(String myFileContentType) {        this.myFileContentType = myFileContentType;    }    public String getMyFileContentType() {        return this.myFileContentType;    }    public void setMyFileFileName(String myFileFileName) {        this.myFileFileName = myFileFileName;    }    public String getMyFileFileName() {        return this.myFileFileName;    }    public void setSavePath(String savePath) {        this.savePath = savePath;    }    public String getSavePath() throws Exception {        return ServletActionContext.getServletContext().getRealPath(savePath);    }    @Override    public String execute() throws Exception {        FileOutputStream fos = null;        FileInputStream fis = null;        try {            System.out.println("myFileFileName:"+myFileFileName);            String myFileNewFileName = UUID.randomUUID() + "_"+myFileFileName;            fos = new FileOutputStream(getSavePath() + "\\" + myFileNewFileName);            fis = new FileInputStream(getMyFile());            byte[] buffer = new byte[1024];            int len = 0;            while ((len = fis.read(buffer)) > 0) {                fos.write(buffer, 0, len);            }            setMyFileFileName(myFileNewFileName);        } catch (Exception ex) {            System.out.println(ex.getMessage());        } finally {            close(fos, fis);        }        return SUCCESS;    }    private void close(FileOutputStream fos, FileInputStream fis) {        if (fis != null) {            try {                fis.close();            } catch (IOException e) {                System.out.println("FileInputStream关闭失败");                e.printStackTrace();            }        }        if (fos != null) {            try {                fos.close();            } catch (IOException e) {                System.out.println("FileOutputStream关闭失败");                e.printStackTrace();            }        }    }}

download.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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 'download2.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">  </head>  <body>  <a href="downSpace/downloadAction?inputPath=/download/car.jpg&contentType=image/jpeg&downFileName=car.jpg">文件下载</a>  <a href="downSpace/downloadAction2">Down Load</a>  </body></html><!-- <html>  <head>    <title>文件下载页面</title>    <meta content="text/html; charset=utf-8" http-equiv=Content-Type>  </head>  <body>    <a href="downloadAction?inputPath=/download/car.jpg&contentType=image/jpeg&downFileName=car.jpg">文件下载</a>    <a href="downloadAction?inputPath=/download/car.jpg&contentType=image/jpeg&downFileName=car.jpg">文件下载</a>    <a href="downloadAction2">Down Load</a>  </body></html> -->

DownloadAction.java

package com.hp.easycar.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 inputPath;    // 代表下载文件的文件类型    private String contentType;    // 代表下载文件的文件名    private String downFileName;    public void setInputPath(String inputPath) throws Exception {        this.inputPath = new String(inputPath.getBytes("iso-8859-1"), "gbk");    }    public String getInputPath() {        return this.inputPath;    }    public void setContentType(String contentType) {        this.contentType = contentType;    }    public String getContentType() {        return this.contentType;    }    public void setDownFileName(String downFileName) throws Exception {        // 处理请求参数的解码        this.downFileName = new String(downFileName.getBytes("iso-8859-1") , "gbk");    }    public String getDownFileName() {        return this.downFileName;    }    public InputStream getDownloadFile() throws Exception {        //ServletContext提供getResourceAsStream()方法        //返回指定文件对应的输入流        return ServletActionContext.getServletContext().getResourceAsStream(inputPath);    }}

DownloadAction2.java

package com.hp.easycar.action;import java.io.FileInputStream;import java.io.InputStream;import javax.servlet.ServletContext;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DownloadAction2 extends ActionSupport{    /**     *      */    private static final long serialVersionUID = 1L;    private String contentType;    private long contentLength;    private String contentDisposition;    private InputStream inputStream;    public String getContentType() {        return contentType;    }    public void setContentType(String contentType) {        this.contentType = contentType;    }    public long getContentLength() {        return contentLength;    }    public void setContentLength(long contentLength) {        this.contentLength = contentLength;    }    public String getContentDisposition() {        return contentDisposition;    }    public void setContentDisposition(String contentDisposition) {        this.contentDisposition = contentDisposition;    }    public InputStream getInputStream() {        return inputStream;    }    @Override    public String execute() throws Exception {        // TODO Auto-generated method stub        //确定各个成员变量的值        contentType="image/jpg";        contentDisposition="attachment;filename=car.jpg";        ServletContext servletContext=ServletActionContext.getServletContext();        /*String fileName=servletContext.getRealPath("/download/car.jpg");        inputStream=new FileInputStream(fileName);*/        inputStream=servletContext.getResourceAsStream("/download/car.jpg");        contentLength=inputStream.available();        return super.execute();    }}

自定义实现文件过滤
自定义实现文件过滤的大体思路。
在UploadAction中增加一个名为allowFileTypes的属性,表示我们所允许上传的文件类型,该属性名可以任意定义,然后实现该属性的setter和getter方法。
在struts.xml文件中为uploadAction添加一个名为allowFileTypes的参数,该参数与UploadAction的allowFileTypes属性一一对应。
在UploadAction中增加一个用于验证文件类型是否合法的方法validateFileType,如果上传文件的类型是allowFileTypes中的类型之一,则说明该文件类型合法,否则不合法。
在execute()方法中调用validateFileType方法,如果验证不通过,则添加一个Field Error信息,并返回input字符串。
在upload.jsp文件的body中,添加一个标签,用于显示Field Error信息。

Struts 2框架对文件下载的支持
Struts 2框架使用org.apache.struts2.dispatcher.StreamResult类型支持文件下载功能,该类型支持以下几个参数。
contentType:下载文件的类型,默认是text/plain。
contentLength:下载文件的长度,以字节为单位,可用于浏览器的进度条显示。
contentDispostion:用于控制文件下载的一些信息,比如下载的文件名,下载时是否弹出下载对话框等。可选的设置包括:inline;filename=”下载的文件名”和attachment;filename=”下载的文件名”。inline是其默认值,可以省略不写,表示下载文件在本页面内部打开,attachment表示弹出文件下载对话框。需要注意的是,当浏览器不支持所下载的文件类型时,即使指定了inline也会弹出文件下载对话框。
inputName:Action中用于返回InputStream的get方法的名字,默认为inputStream。如果使用默认值,则在Action中必须实现一个名为getInputStream的方法。

0 0
原创粉丝点击