16_struts2_2文件上传和下载

文件上传 ———源码位置 day31_struts2_3

1. 浏览器端:
    1. method=post
    2. <input type="file" name="xx">
    3. encType="multipart/form-data";

2. 服务器端:
    com-fileupload组件
    1. DiskFileItemFactory
    2. ServletFileUpload
    3. FileItem

3. struts文件上传步骤:
    jsp 页面:<input type="file" name="upload">

    action 中三个属性
        private File upload;
        private String uploadContentType;
        private String uploadFileName;

    在execute方法中使用commons-io包下的FileUtils完成文件复制
        FileUtils.copyFile(upload,new File("e:/upload",uploadFileName));

4. 注意事项

    1. 如果是多个文件上传:

        aciton中如下处理:(将字段全部转化为List数组形式)
                    private List<File> upload;
                    private List<String> uploadContentType;
                    private List<String> uploadFileName;

                    @Override
                    public String execute() throws Exception {

                        for (int i = 0; i < uploadContentType.size(); i++) {
                            System.out.println("上传的文件类型是:" + uploadContentType.get(i));
                            System.out.println("上传的文件名称" + uploadFileName.get(i));
                            FileUtils.copyFile(upload.get(i), new File("e:/upload",
                                    uploadFileName.get(i)));
                        }

                        return null;
                    }

    2. 文件控制
        总文件上传大小控制: struts.xml 文件中加入这个,设置大小
            <constant name="struts.multipart.maxSize" value="209714520"></constant>
        单个文件控制
            大小:<param name="maximumSize">2097152</param>
            类型:<param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
            源码赏析:
                    <action name="upload" class="com.uu.action.UploadAction">
                        <result name="input">upload.jsp</result>
                        <interceptor-ref name="defaultStack">
                            <param name="maximumSize">2097152</param>
                            <!--Ognl 表达式  -->
                            <param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
                        </interceptor-ref>
                    </action>

    3. 错误信息提示
        如果出现问题,需要配置input视图,在页面上可以通过<s:actionerror/>展示
        若要国际化,如下操作
        默认设置:
        struts-messages.properties 文件里预定义 上传错误信息,通过覆盖对应key 显示中文信息
            struts.messages.error.uploading=Error uploading: {0}
            struts.messages.error.file.too.large=The file is to large to be uploaded: {0} "{1}" "{2}" {3}
            struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
            struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
        修改为:(在src下创建message.properties文件,内容如下)
            struts.messages.error.uploading=上传错误: {0}
            struts.messages.error.file.too.large=上传文件太大: {0} "{1}" "{2}" {3}
            struts.messages.error.content.type.not.allowed=上传文件的类型不允许: {0} "{1}" "{2}" {3}
            struts.messages.error.file.extension.not.allowed=上传文件的后缀名不允许: {0} "{1}" "{2}" {3}

        注意:记得在struts.xml文件中配置
            <constant name="struts.custom.i18n.resources" value="message"></constant>

    4. 其他上传方式
        # struts.multipart.parser=cos
        # struts.multipart.parser=pell
        struts.multipart.parser=jakarta

        如果使用pell,cos进行文件上传,必须导入其jar包.

action源码

`

package com.uu.action;
import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
    private List<File> upload;
    private List<String> uploadContentType;
    private List<String> uploadFileName;

    public List<File> getUpload() {
        return upload;
    }

    public void setUpload(List<File> upload) {
        this.upload = upload;
    }

    public List<String> getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(List<String> uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public List<String> getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(List<String> uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    @Override
    public String execute() throws Exception {

        for (int i = 0; i < uploadContentType.size(); i++) {
            System.out.println("上传的文件类型是:" + uploadContentType.get(i));
            System.out.println("上传的文件名称" + uploadFileName.get(i));
            FileUtils.copyFile(upload.get(i), new File("e:/upload",
                    uploadFileName.get(i)));
        }

        return null;
    }
}

`

文件下载

1. 下载步骤:
    1. jsp 中
            <a href="${pageContext.request.contextPath }/download?filename=曹颖 - 喜欢你.mp3">曹颖 - 喜欢你.mp3</a><br>
            <a href="${pageContext.request.contextPath }/download?filename=陈冠蒲 - 太多(穿越版).mp3">陈冠蒲 - 太多(穿越版).mp3</a><br>
            <a href="${pageContext.request.contextPath }/download?filename=动力火车 - 终于明白.mp3">动力火车 - 终于明白.mp3</a>

    2. action中
        private String filename;//提供get和set方法(方便框架赋值)



    3. struts.xml 中配置
        <action name="download" class="com.uu.action.DownloadAction">
            <result type="stream">
                <param name="contentType">${contentType}</param>
                <param name="contentDisposition">attachment;filename=${downloadFileName}</param>
                <param name="inputStream">${inputStream}</param>
            </result>
        </action>

        注意:${}中的值在Action中必须提供javaBean (就是get,set 必须得有一个才能被使用,在这个只写get就可以)

    4.  注意事项
        1. 文件下载<result type="stream"> type 必须是stream

        2. contentType,contentDisposition ,inputStream 三个属性一般必须有,不要在配置文件中乱改(特殊情况除外)
            <result type="stream">
                <param name="contentType">text/plain</param>
                <param name="contentDisposition">attachment;filename=a.txt</param>
                <param name="inputStream">${inputStream}</param> 会调用当前action中的getInputStream方法。
            </result>

        3. 下载点击后,取消下载,服务器端会产生异常。
            在开发中,解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。

action下载源码

    package com.uu.action;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;

    import org.apache.struts2.ServletActionContext;

    import com.opensymphony.xwork2.ActionSupport;
    import com.uu.utils.DownloadUtils;

    public class DownloadAction extends ActionSupport {
        private String filename;

        public String getFilename() {
            return filename;
        }

        public void setFilename(String filename) {
            this.filename = filename;
        }

        /**
         * 设置下载文件mimeType类型
         */
        public String getContentType() {
            String mimeType = ServletActionContext.getServletContext().getMimeType(
                    filename);
            return mimeType;
        }

        /**
         * 获取文件名称
         */
        public String getDownloadFileName() throws UnsupportedEncodingException {
            return DownloadUtils.getDownloadFileName(ServletActionContext
                    .getRequest().getHeader("user-agent"), filename);
        }

        /**
         * 得到文件的输入流
         */
        public InputStream getInputStream() throws UnsupportedEncodingException,
                FileNotFoundException {
            filename = new String(filename.getBytes("iso8859-1"), "utf-8");
            FileInputStream fis = new FileInputStream("e:/upload/" + filename);
            return fis;
        }

        @Override
        public String execute() throws Exception {
            System.out.println("进行下载.............................");
            return SUCCESS;
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值