您的位置:首页 > 编程语言 > Java开发

struts2单文件,多文件上传

2015-11-18 10:54 387 查看
上传的页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
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 'login4.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <s:form action="uploadAction!upload.action" method="post" enctype="multipart/form-data" >
   <s:file label="上传" theme="simple" name="upload"/>
   <s:submit value="上传"/>
</s:form>
  </body>
</html>


上传的action

package edu.cylg.rg.ssh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	// 封装单个上传文件域的属性
	private File upload;
	// 封装单个上传文件类型的属性
	private String uploadContentType;
	// 封装单个上传文件名的属性
	private String uploadFileName;
	// 动态设置上传文件保存地址
	private String savePath;

	public String getSavePath() {
		// return ServletActionContext.getRequest().getRealPath("");
		String onload = "C:\\report\\cached\\";
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("onload", onload);
		// return ServletActionContext.getRequest().getContextPath();
		return onload;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	// 上传单个文件的文件类型的setter和getter方法
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadContentType() {
		return (this.uploadContentType);
	}

	// 上传单个文件的文件名的setter和getter方法
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadFileName() {
		return (this.uploadFileName);
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
		// savePath = ServletActionContext .getRequest().getRealPath("");
	}

	// 上传单个文件
	public String upload() {
		try {
			// 以服务器的文件保存地址和原文件名建立上传文件输出流
			System.out.println(ServletActionContext.getRequest()
					.getRealPath("")
					+ File.separator
					+ "images"
					+ File.separator + getUploadFileName() + "路径");
			File uploadPath=new File(ServletActionContext
					.getRequest().getRealPath("")
					+ File.separator
					+ "images");
			if(!uploadPath.exists()){
				uploadPath.mkdir();
			}
			FileOutputStream fos = new FileOutputStream(uploadPath+ getUploadFileName());
			// 以上传文件建立一个文件上传流
			FileInputStream fis = new FileInputStream(getUpload());
			// 将上传文件的内容写入服务器
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
}


这里上传文件,文件名,文件类型的命名规则要跟上传表单的name一致,格式不能改变。

struts.xml

<action name="uploadAction" class="edu.cylg.rg.ssh.action.UploadAction">
			<!-- 配置fileUpload的拦截器 -->   
                 <interceptor-ref name="fileUpload">   
                            <!-- 配置允许上传的文件类型 -->   
                   <param name="allowedTypes">   
                      image/bmp,image/png,image/gif,image/jpeg,image/jpg,application/msword,text/plain   
                   </param>   
                            <!-- 配置允许上传的文件大小 -->   
                   <param name="maximumSize">2000000000</param>   
                 </interceptor-ref>   
                 <interceptor-ref name="defaultStack" />   
			<result name="input">/index.jsp</result>
			<result name="success">/login.jsp</result>
		</action>


多文件上传

<s:fielderror></s:fielderror>
                <!--  <input type="button" onclick="addComponent();" value="在上传一个" name="button" />  --> 
                <br />
                <s:form action="uploadactions"  method="post" enctype="multipart/form-data">
                         <s:file name="upload" label="路径"/>
                         <s:file name="upload" label="路径"/>
                         <s:file name="upload" label="路径"/>
                        <s:submit value="上传"/>
                </s:form>


struts.xml

<action name="uploadactions" class="com.butone.struts2.taguser.UploadActions" method="upload">
       <!-- 配置fileUpload的拦截器 -->   
            <interceptor-ref name="fileUpload">   
                <!-- 配置允许上传的文件类型 -->   
                <param name="allowedTypes">   
                    image/bmp,image/png,image/gif,image/jpeg,image/pjpeg,image/jpg,application/msword,text/plain 
                </param>   
                <!-- 配置允许上传的文件大小 -->   
                <!-- <param name="maximumSize">2000000000</param>  -->   
            </interceptor-ref>   
            <interceptor-ref name="defaultStack" />  
   <result>/taguser/fileuploadoutput.jsp</result>
   <result name="input">/taguser/fileuploads.jsp</result>
  </action>


UploadActions.java

public class UploadActions extends ActionSupport { 
 
 //封装多个上传文件域的属性   
    private List<File> upload = new ArrayList<File>();   
    // 封装多个上传文件类型的属性   
    private List<String> uploadContentType = new ArrayList<String>();   
    // 封装多个上传文件名的属性   
    private List<String> uploadFileName = new ArrayList<String>();   
       
    //动态设置上传文件保存地址   
    private String savePath;   
       
    public String getSavePath() { 
     System.out.println("getSavePath()!!!!!");
     
     System.out.println(savePath+"++++++++++++++++++++++++++++++");
        return savePath;   
    }   
  
    public void setSavePath(String savePath) {
     System.out.println("setSavePath()!!!!!");
        this.savePath = savePath;
       // savePath = "E:\\butone\\struts2.2\\WebRoot\\images\\"+getUploadFileName();
    }     
  
    //上传多个文件对应文件内容的setter和getter方法   
    public List<File> getUpload() {   
        return upload;   
    }   
    public void setUpload(List<File> upload) { 
     System.out.println("----------------    setUpload(List<File> upload)     ----------------");
        this.upload = upload;   
    }   
       
    //  上传多个文件的文件类型setter和getter方法    
    public List<String> getUploadContentType() {   
        return uploadContentType;   
    }   
    public void setUploadContentType(List<String> uploadContentType) {   
        this.uploadContentType = uploadContentType;   
    }   
  
    // 上传多个文件的文件名的setter和getter方法    
    public List<String> getUploadFileName() {   
        return uploadFileName;   
    }   
    public void setUploadFileName(List<String> uploadFileName) {   
        this.uploadFileName = uploadFileName;   
    }   
  
    public String upload() {   
     
     //savePath = "E:\\butone\\struts2.2\\WebRoot\\images\\";
     savePath = ServletActionContext.getRequest().getRealPath("");
     
     System.out.println("upload()!!!!!");
        //上传多个文件   
        List<File> files = getUpload();   
        // String ext ="";   
        FileOutputStream fos = null;   
        FileInputStream fis = null;   
        byte[] buffer = new byte[1024];   
        int len = 0;   
        Random rd = new Random();   
        System.out.println(files.size()+"               ----------------");
        System.out.println(getSavePath());
        for (int i = 0; i < files.size(); i++) {   
            try {   
                //以服务器的文件保存地址和当前时间组合文件名建立上传文件输出流   
                // ext =uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf('.'));   
                 /* fos = new FileOutputStream(getSavePath()+ File.separator+  
                 * DateFormatUtil.getCurrentCustomFormatDateTime(DateFormatUtil.DATE_TIME_FORMAT_14) +  
                 * String.valueOf(rd.nextInt(1000))+ext);  
                 */  
             System.out.println(getSavePath()+"------------------------getsavepath!!!");
                fos = new FileOutputStream(getSavePath() + File.separator   
                        + uploadFileName.get(i));   
                // 以上传文件建立一个文件上传流   
                fis = new FileInputStream(files.get(i));   
                // 将上传文件的内容写入服务器   
                len = 0;   
                while ((len = fis.read(buffer)) > 0) {   
                    fos.write(buffer, 0, len);   
                }   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
         return SUCCESS;   
    }   
}


fileuploadoutput.jsp

<!-- 输出上传的表单里的文件标题属性 -->   
         文件路径:<s:property value="savePath" /><br> 
               <s:property value="#request.onload" /> <br> 
       <!-- 根据上传文件的文件名,在页面上显示上传的图片 -->   
         文件为:<s:property value="uploadFileName"/><br>  
         
        <s:iterator value="uploadFileName">
         <img src="<s:property />" />
         <!-- 就是为了打印图片名称,但好像不支持中文图片的 -->
         <s:property/>
        </s:iterator>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: