struts2实现文件上传与下载

一、单文件上传

1、文件上传条件:
(1)请求方法必须是post
(2)enctype的属性值必须为multipart/form-data
(3)提供一个文件选择域
2、文件上传jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传title>
head>
<body>
    <s:actionerror/>
    <s:form action="upload.action" enctype="multipart/form-data">
        <s:textfield name="userName" label="用户名"/>
        <s:file name="photo" label="照片"/>
        <s:submit value="上传"/>
    s:form>
body>
html>

3、文件上传编写动作类注意:
(1)struts2提供的上传文件名命名规则:上传的字段名(form表单中的)+fileName
(2)struts2提供MIME类型命名规则:上传的字段名(form表单中的)+contentType
(3)没有使用模型驱动时:form表单提供的属性和struts2提供的属性要生成set和get方法
4、上传文件动作类代码

package com.san.action;
import java.io.File;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Upload extends ActionSupport{
    private static final long serialVersionUID = 1L;
    //表单提供的属性
    private String userName;
    private File photo;
    //struts2在文件上传时提供的属性
    private String photoFileName;//上传的文件名(上传的字段名+fileName)
    private String photoContentType;//上传文件的MIME类型(上传的字段名+contentType)
    public String upload(){
        //1、拿到servletContext
        ServletContext application=ServletActionContext.getServletContext();
        //String filePath=application.getRealPath("/WEB-INF/files");
        //2、调用realPath方法,获取一个虚拟目录而得到一个真实的目录
        String filePath=application.getRealPath("/WEB-INF/files");
        File file=new File(filePath);
        //3、如果真实目录不存在则创建
        if(!file.exists()){
            file.mkdirs();
        }
        //4、把photo存过去
        photo.renameTo(new File(file,photoFileName));
        return null;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public File getPhoto() {
        return photo;
    }
    public void setPhoto(File photo) {
        this.photo = photo;
    }
    public String getPhotoFileName() {
        return photoFileName;
    }
    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }
    public String getPhotoContentType() {
        return photoContentType;
    }
    public void setPhotoContentType(String photoContentType) {
        this.photoContentType = photoContentType;
    }
}

5、编写struts.xml配置文件注意:
(1)上传文件默认为2兆,修改上传限制时,value的值应该是算出来的,不能写成这种形式1024*1024*5(修改为5兆)
(2)限制文件的扩展名时,如果有多个限制条件用逗号隔开
(3)限制文件的MIME时,如果有多个条件时用逗号隔开;jpg形式的图片写成jpeg不能写成jpg
6、struts.xml代码



<struts>
    
    <constant name="struts.ognl.allowStaticMethodAccess" value="true">constant>
    
    <constant name="struts.devMode" value="true">constant>
    
    <constant name="struts.multipart.maxSize" value="5242880">constant>
    
    <constant name="struts.custom.i18n.resources" value="fileupload_message">constant>
    <package name="p1" extends="struts-default">

        
        <action name="upload" class="com.san.action.Upload" method="upload">
            
             
             <interceptor-ref name="defaultStack">
                <param name="fileUpload.allowedTypes">image/jpegparam>
             interceptor-ref>
            <result name="input">upload.jspresult>
        action>
    package>
struts>

7、将不符合条件的上传的英文提示改为中文提示
(1)创建一个properties文件

struts.messages.error.content.type.not.allowed=\u8F93\u5165\u6B63\u786E\u7684\u5404\u5F0F\: {0} "{1}" "{2}" {3}

(2)struts.xml中,配置全局资源包


<constant name="struts.custom.i18n.resources" value="fileupload_message">constant>

(3)效果如下:
struts2实现文件上传与下载_第1张图片
struts2实现文件上传与下载_第2张图片

二、多文件上传

1、只需要修改动作类中代码,其他的不变;代码如下

private String userName;
    private File[] photo;
    //struts2提供的两个属性
    private String[] photoFileName;//文件名(表单字段属性+fileName)
    private String[] photoContentType;//文件MIME属性
    public String upload2(){
        ServletContext application=ServletActionContext.getServletContext();
        //获取路径
        String filePath=application.getRealPath("/WEB-INF/files2");
        //判断路径是否存在
        File file=new File(filePath);
        if(!file.exists()){
            //路径不存在时,创建
            file.mkdirs();
        }
        //遍历把文件剪切到创建的文件中
        for(int i=0;inew File(file,photoFileName[i]));
        }
        return null;
    }

三、文件下载

1、文件下载的struts.xml配置代码

<package name="p2" extends="struts-default">
        <action name="download" class="com.san.action.Download" method="download">
            
            <result name="success" type="stream">
                
                <param name="contentType">application/octet-streamparam>
                
                <param name="contentDisposition">attachment;filename=1.jpgparam>
                
                <param name="inputName">inputStreamparam>
            result>
        action>
    package>

2、文件下载的动作类代码

package com.san.action;

import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Download extends ActionSupport{
    private static final long serialVersionUID = 1L;
    //指定InputStream的名称时,不能使用in
    private InputStream inputStream;
    //创建一个文件名属性
    private String filename;
    public String download() throws Exception{
        //1、找到文件存储位置
        String filePath=ServletActionContext.getServletContext().getRealPath("/WEB-INF/files/1.jpg");
        //2、把文件读入到InputStream流中
        inputStream=new FileInputStream(filePath);
        //3、给文件名赋值
        filename="照片.jpg";
        return SUCCESS;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getFilename() {
        return filename;
    }
    public void setFilename(String filename) {
        this.filename = filename;
    }
}

你可能感兴趣的:(Struts2)