使用Struts进行文件上传

对于单个文件进行上传
在jsp页面设置

<s:form action="upload/benxi_upload.sxt" enctype="multipart/form-data">
    <s:textfield name="title" label="主题"/>
    <s:file name="img"/>
    <s:submit value="上传"/>
</s:form>

xml文件中配置文件信息:

<package name="upload" extends="struts_basic" namespace="/upload">

    <action name="benxi_*" class="com.sxt.action.fileUpload" method="{1}">
        <!-- 通过fileUpload拦截器来限制上传文件额类型和大小 -->
        <interceptor-ref name="defaulStack">
            <param name="allowedExtensionSet">jpg,bmp,gif,png</param>
            <param name="allowedTypesSet">images/jpeg,images/bmp,images/gif,images/png</param>
            <param name="maximumSize">1024*1024*5</param>
        </interceptor-ref>

        <result name="success">/showFile.jsp</result>
        <!-- 下载,设置类型为stream流 -->
        <result name="download" type="stream">
            <param name="allowCaching">true</param>
            <param name="contentCharSet">utf-8</param>
            <param name="inputName">is</param>
            <!-- 描述及文件类型 -->
            <param name="contentDisposition">attackment;filename=${fileName}</param>
            <param name="contentType">${imgsContentType}</param>
        </result>
    </action>
</package>

fileUpload.java文件

public class fileUpload extends ActionSupport{
    //获取name为title的值
    private String title;
    //imgs为图片的name值,imgsFileName和imgsContentType为特定值
    private File img;
    private String imgFileName;
    private String imgContentType;

    //设置文件名,方便获取
    private String fileName;
    //设置输出流,给Struts2内置保存文件机制下载文件
    private InputStream is;

    public String upload() throws IOException{
        /*
         * 修改文件名(当前日期(20171010)+6位随机数) 
         * 随机生成唯一的字符串(UUID)
         * 生成的码:356ed920-97ab-416c-873d-1e58a886af36
         * 获取一个新的文件名称,用于保存文件信息
         */
        fileName = UUID.randomUUID().toString().replace("-", "")+
                imgFileName.substring(imgFileName.lastIndexOf("."));
        //获取绝对路径
        String filePath = ServletActionContext.getServletContext().
                getRealPath("/upload/image/img");
        //查看是否存在此路径,不存在则创建一个。因为文件路径不存在可以这样创建,而文件则不会被创建
        File filedir = new File(filePath);
        if(!filedir.exists())
            filedir.mkdirs();
        //创建该文件,需要分开创建
        File file = new File(filedir, fileName);
        //开始复制文件
        FileUtils.copyFile(img, file);

        return this.SUCCESS;
    }

    public String download() throws FileNotFoundException{
        //文件下载源码位置:org.apache.struts2.interceptor.FileUploadInterceptor.class
        //获取绝对路径
        String filePath = ServletActionContext.getServletContext().
                getRealPath("/upload/image/img");
        is = new FileInputStream(new File(filePath+"/"+fileName));
        return "download";
    }

    get/set方法省略 

}

另外一个页面进行显示:

<body>
<s:property value="title"/>
<hr>
<img alt="" src="image/img/<s:property value='fileName'/>"/>
<hr>
<a href="upload/benxi_download.sxt?fileName=<s:property value='fileName'/>">下载</a>
</body>

多个文件上传
对于上传多张图片和下载,只需要把几个参数改变成为数组就可。

public class UploadAction extends ActionSupport {
    private String title;
    private String desc;
    //imgs为图片的name值,imgsFileName和imgsContentType为特定值
    private File imgs[];
    private String imgsFileName[];
    private String imgsContentType[];
    //设置形参作为图片名
    private String fileName[];
    private InputStream is;
    public String upload() throws Exception {
        fileName = new String[imgs.length];

        for(int i = 0;i < imgs.length;i++){
            //修改文件名(当前时间+6位数随机数)
            //随机生成唯一的字符串(UUID),得到的是StringBuffer
            fileName[i] = UUID.randomUUID().toString().replace("-", "")+
                    imgsFileName[i].substring(imgsFileName[i].lastIndexOf("."));
            //获取项目的绝对路径、upload/images.如果文件有命名空间,则需要在绝对路径前面加上命名
            String filepath = ServletActionContext
                    .getServletContext().getRealPath("/upload/upload/images");
            File filedir = new File(filepath);
            //构建目录
            if(!filedir.exists())
                filedir.mkdirs();
            //创建文件
            File file = new File(filedir,fileName[i]);
            //文件拷贝
            FileUtils.copyFile(imgs[i], file);
        }
        return this.SUCCESS;
    }
其他代码省略

上传的jsp页面:

<s:form action="upload/benxi_upload.sxt" enctype="multipart/form-data">

    <s:textfield name="title" label="标题:"/>
    <s:textfield name="desc" label="描述:"></s:textfield> 
    <s:file name="imgs"/>
    <s:file name="imgs"/>
    <s:submit value="立即上传"/>
</s:form>

显示的jsp页面:

<s:if test="fileName!=null && fileName.length>0">
使用数据迭代器把内容遍历输出。其中数组使用的变量名为status,
<s:iterator value="fileName" status="file">
    <img alt="" src="upload/images/<s:property value="fileName[#file.index]"/>" width="300px" height="300px"/>
    <a href="upload/benxi_download.sxt?fileName=<s:property/>">下载</a>
    <hr>
</s:iterator>
</s:if>
<s:else>没有值</s:else>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值