単一ファイルアップロードの2つの方法の例


      :

1、    web  ,  struts2      jar,   



    



            

2、  Action 

     


package com.ljq.action;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
    
    private File image; //     
    private String imageFileName; //    
    private String imageContentType; //    

    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        //D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
        System.out.println("realpath: "+realpath);
        if (image != null) {
            File savefile = new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            ActionContext.getContext().put("message", "      ");
        }
        return "success";
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    
}

            

     


package com.ljq.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport {

    //           
    private File image;
    //            
    private String imageContentType;
    //           
    private String imageFileName;
    //          
    private String savePath;

    @Override
    public String execute() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            //        
            System.out.println(getSavePath());
            fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());
            //        
            fis = new FileInputStream(getImage());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("      ");
            e.printStackTrace();
        } finally {
            close(fos, fis);
        }
        return SUCCESS;
    }

    /**
     *            
     * 
     * @return
     */
    public String getSavePath() throws Exception{
        return ServletActionContext.getServletContext().getRealPath(savePath); 
    }

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

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    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();
            }
        }
    }

}

              

struts.xml    


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!--        Struts2       ,        action,     *.action     Struts2  。
                      ,            (,)  。 -->
    <constant name="struts.action.extension" value="do" />
    <!--              ,    true(       ),         -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!--  struts        ,             ,    false(       ),         -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!--        ,                -->
    <constant name="struts.devMode" value="true" />
    <!--         -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--        -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!--               。    2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!--             ,    javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
    
         
    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
    
    <package name="upload2" extends="struts-default">
        <action name="upload2" class="com.ljq.action.UploadAction2" method="execute">
            <!--     savePath     -->
            <param name="savePath">/images</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
            <result name="input">/upload/upload.jsp</result>
            <interceptor-ref name="fileUpload">
                <!--      -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!--     ,        -->
                <param name="maximumSize">1025956</param>
            </interceptor-ref>
            <!--          fileUpload  ,     -->
            <interceptor-ref name="defaultStack" />
        </action>
    </package>
</struts>

           

      


<%@ 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 http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>

    <body>
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <form action="${pageContext.request.contextPath}/upload2/upload2.do" 
              enctype="multipart/form-data" method="post">
              :<input type="file" name="image">
                <input type="submit" value="  " />
        </form>
        <br/>
        <s:fielderror />
    </body>
</html>

           

      


<%@ 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 http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>
  
  <body>
        !
    <br/><br/>
    <!-- ${pageContext.request.contextPath} tomcat    ,
           :D:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->
    <img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
    <s:debug></s:debug>
  </body>
</html>