备份_文件上传(图片上传)

20:49:25

1.succ.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix = "s" uri ="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Succ</title>
</head>
<body>
上传成功
<div>
文件为:<s:property value="file"/>
<img src="<s:property value="'upload/'+uploadFileName"/>"/>
</br>
</div>


</body>
</html>

2.UploadAction.java

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.omg.CORBA.PRIVATE_MEMBER;

import com.opensymphony.xwork2.ActionSupport;

import jdk.nashorn.internal.ir.RuntimeNode.Request;

public class UploadAction extends ActionSupport {
    private File upload;
    private String uploadContentType;
    private String uploadFileName;
    private String savePath;
    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }
    public String getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public String getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath("/WEB-INF"+savePath);
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    @Override
    public String execute() throws Exception {
        if(uploadFileName!=null){
            FileOutputStream fos =new FileOutputStream(getSavePath()+"\\"+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);
            }
            System.out.println("uploadFileName"+uploadFileName);
            FileUtils.copyFile(upload,new File("d://"+uploadFileName));
        }else{
            System.out.println("uploadFileName"+uploadFileName);
        }
        
        return SUCCESS;
    }

}

3.upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix = "s" uri ="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload file</title>
</head>
<body>

<s:form action="upload.action" enctype="multipart/form-data">
<s:file name="upload" label="选择文件"/></br>
<s:submit value="上传"/>
</s:form>
</body>
</html>

4.struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<!-- 注意:编程或运行时要联网 -->
<struts>
    <!-- namespace:URL的前缀,extends:扩展或继承自,struts-default -->
    <constant name="struts.custom.i18n.resources" value="mess"/>
    <constant name="struts.i18n.encoding" value="Utf-8"/>
    
    <package name="abc" namespace="/" extends="struts-default"><!--  package="?"?为模块的名字,并且需要继承struts-default -->

    <interceptors>
        <interceptor name="checkLogin" class="action.LoginInterceptor"></interceptor>
        <interceptor-stack name="myInterceptorStack"> 
                <interceptor-ref name="checkLogin"></interceptor-ref> 
                <interceptor-ref name="defaultStack"></interceptor-ref> 
         </interceptor-stack> 
    </interceptors>
    
    <default-interceptor-ref name="myInterceptorStack"></default-interceptor-ref>
    <global-results>
            <result name="Login22">/Login.jsp</result>
    </global-results>
    
        <action name="Login" class="action.Loginaction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="success">/succ.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="fair" type="redirect">/fair.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
        
        <action name="Login2" class="action.Loginaction2"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="success">/Query.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="fair" type="redirect">/Login.jsp</result>
            <result name="admin" type="redirect">/product_manage.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
        
        <action name="register" class="action.registeraction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <result name="success">/Login.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="fair" type="redirect">/register.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
        
        <action name="Query" class="action.Dispartaction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="success">/Dispart.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="fair" type="redirect">/Query.jsp</result>
            <result name="input">/Query.jsp</result>
        </action>
        
        <action name="product_manager_add" class="action.product_addaction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="add">/commodity_add.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="input">/product_manager.jsp</result>
        </action>
         
         <action name="product_manager_delete" class="action.product_deleteaction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="delete">/commodity_delete.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="input">/product_manager.jsp</result>
        </action>
        
        <action name="product_manager_check" class="action.product_checkaction"><!-- 原来这里的class需要用的是需要调用的全路径名,一个struts的请求就是一个action -->
            <!-- 注意大小写一致 -->
            <result name="check">/user.jsp</result><!-- 这里的name就是给提交到这里的action就是相应 -->
            <result name="input">/product_manager.jsp</result>
        </action>
    </package>
    <package name="lee" extends="struts-default">
        
        
        <action name="upload" class="action.UploadAction">
        <param name="savePath">/upload</param>
        <result name="success">/succ.jsp</result>
        <result name="input">/upload.jsp</result>
            
        </action>
    </package>
</struts>

2018-05-25

Uploadaction.java

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.omg.CORBA.PRIVATE_MEMBER;

import com.mysql.cj.api.Session;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import jdk.nashorn.internal.ir.RuntimeNode.Request;

public class UploadAction extends ActionSupport {
	private String filename; 
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private String savePath;
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath("/"+savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	@Override
	public String execute() throws Exception {
		/*if(uploadFileName!=null){
			FileOutputStream fos =new FileOutputStream(getSavePath()+"\\"+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);
			}
			System.out.println("uploadFileName"+uploadFileName);
			FileUtils.copyFile(upload,new File("d://"+uploadFileName));
			ActionContext context = ActionContext.getContext(); //Action上下文
			//ActionContext包含所有与Web容器相关的对象
			//Map session = context.getSession();
			Map<String, Object> session = context.getSession();
			session.put("uploadFileName",uploadFileName);
		}else{
			System.out.println("uploadFileName"+uploadFileName);
		}*/
		 File dir = new File(getSavePath());  
	        if(!dir.exists()) dir.mkdir();  
	        File f = new File(getSavePath() + "\\" + getUploadFileName());  
	        FileOutputStream fos = new FileOutputStream(f);  
	        FileInputStream fis = new FileInputStream(getUpload());  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        while((len = fis.read(buffer)) > 0){  
	            fos.write(buffer,0,len);  
	        }  
	     
		return SUCCESS;
	}

}

  struts:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<!-- 注意:编程或运行时要联网 -->
<struts>
    <!-- namespace:URL的前缀,extends:扩展或继承自,struts-default -->
    <package name="abc" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name="loginInterceptor" class="interceptor.LoginInterceptor"></interceptor>
            <interceptor-stack name="loginInterceptorStack">
                <interceptor-ref name="loginInterceptor"/>
                <interceptor-ref name="defaultStack"/>

            </interceptor-stack>
        </interceptors>
        
        <!-- <default-interceptor-ref name="loginInterceptorStack"/> -->
        
        <global-results>  
            <result name="login">/Login.jsp</result>  
        </global-results>  
        
        <action name="Login" class="action.LoginAction">
            <!-- 注意大小写一致 -->
            <result name="loginfail">/Login_fail.jsp</result>
            <result name="mainshop" >/main_shop.jsp</result>
            <result name="checkfail" >/Checkcode_fail.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
        <action name="Register" class="action.RegisterAction">
            <result name="registerfail">/Register_fail.jsp</result>
            <result name="registersuccess">/Register_success.jsp</result>
            <result name="checkfail2">/Checkcode_fail2.jsp</result>
        </action>
        <action name="admin" class="action.AdminAction">
            <result name="loginfail">/Login_fail.jsp</result>
            <result name="bsm">/Bsm.jsp</result>
            <result name="checkfail">/Checkcode_fail.jsp</result>
        </action>
        <action name="addbooks" class="action.AddbookAction">
            <interceptor-ref name="loginInterceptorStack"/>
            <result name="bsm">/Bsm.jsp</result>
        </action>
        
        <action name="Upload" class="action.FileUploadAction">  
            <interceptor-ref name="loginInterceptorStack"/>
            <interceptor-ref name="fileUpload">   <!--配置fileUpload的拦截器-->
            <param name="allowedTypes"> image/bmp,image/png,image/gif,image/jpeg </param>   <!--配置允许上传的文件类型-->     
            <param name="maximumSize">5242880</param>      <!--配置允许上传的文件大小单位字节-->  
            </interceptor-ref>  
            <interceptor-ref name="defaultStack"/>  
            <param name="savePath">/upload</param>
            <result name="success" >/main_shop.jsp</result>
            <result name="input">/FileUpload.jsp</result>
            <!-- <result name="login">/Login.jsp</result> -->
        </action>
        
    </package>
</struts>

upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix = "s" uri ="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload file</title>
</head>
<body>

<s:form action="upload.action" enctype="multipart/form-data">
<s:file name="upload" label="选择文件"/></br>
<s:submit value="上传"/>
</s:form>
</body>
</html>

 Login.jsp:

  1 <%@ page language="java" contentType="text/html; charset=utf-8"
  2     pageEncoding="utf-8"%>
  3      <%@ taglib prefix = "s" uri ="/struts-tags" %>
  4 <!doctype html>
  5 <html>
  6 <head>
  7 <meta charset="utf-8">
  8 <title>验证码</title>
  9 <style>
 10 form{padding:0px 15px 15px 120px;}  
 11 form{width:500px;height:300px;} 
 12 form fieldset{border:0;align:center;} 
 13 form label{display:inline-block;width:60px;text-align:right}  
 14 input{width:240px;height:30px;}    
 15 #code{  
 16                 font-family:Arial;  
 17                 font-style:italic;  
 18                 font-weight:bold;  
 19                 border:0;  
 20                 letter-spacing:2px;  
 21                 color:blue; 
 22                 width:50px;
 23                 height:40px; 
 24             }
 25 
 26 #box{position:fixed;left:0px;right:0px;width:600px;margin-left:auto;margin-right:auto;top:100px;} 
 27 #submit{
 28     position:absolute;
 29     left:200px;
 30     right:300px;    
 31 }
 32 </style>
 33 <script>
 34  var code;
 35     function createCode(){
 36         code = '';                        //首先默认code为空字符串
 37         var codeLength = 4;
 38         var codeV = document.getElementById('code');
 39    
 40         var random = new Array(0,1,2,3,4,5,6,7,8,9);
 41         for(var i = 0; i < codeLength; i++){//设置随机数范围,这设置为0 ~ 10
 42              var index = Math.floor(Math.random()*10);
 43              code += random[index]; 
 44         }
 45         codeV.value = code;                 //将拼接好的字符串赋值给展示的Value
 46     }
 47     function validate(){
 48         var oValue = document.getElementById('input').value.toUpperCase();
 49         if(oValue ==0){
 50             alert('请输入验证码');
 51         }else if(oValue != code){
 52             alert('验证码不正确,请重新输入');
 53             oValue = ' ';
 54             request.getRequestDispatcher("Login.jsp").forward(request, response);
 55             createCode();
 56         }
 57     }
 58     window.onload = function (){
 59         createCode();
 60     }
 61  </script>
 62 </head>
 63 
 64 <body>
 65 <div id="box">
 66 
 67 <h1 style="font-size:20x;font-family:'微软雅黑';">用户登录</h1>
 68         <form action= "Login2.action" method = "post" style="background:#cccccc">
 69         
 70       <fieldset>
 71       <label>用户名:</label>
 72       <input type ="text" name = "username" required="required">
 73             <p>
 74             <label>密码:</label>
 75             <input type="password" name = "password" required="required">
 76             </p>
 77             <p>
 78             <label>验证码</label>
 79             <input type = "text" name="certify2" id = "input" value="" required="required"/>  
 80             <input type = "button" id="code" onclick="createCode()"/>              
 81             </p>
 82             <p>  
 83                 <a href="register.jsp">没注册</a>  
 84               </p>  
 85               <p >
 86                <input type = "submit" value = "Login" name="submit"  id="submit" onclick="validate()"> 
 87             </p>
 88         </center>
 89       </fieldset>    
 90     </form>
 91 
 92 </center>
 93 <div>
 94 
 95 <button onclick="window.location.href='FileUpload.jsp'">上传头像</button> 
 96 </div>
 97 </div>
 98 <%
 99 String uploadFilename = (String)session.getAttribute("uploadFileName");
100 if(uploadFilename!=null){
101 
102 %>
103 <div>
104 <s:property value="FileName"/>
105  <img src="<s:property value = "'upload/'+ uploadFileName"/>"/>   
106 </br>
107 </div>
108 <%
109 
110 
111 }
112 %>
113 
114 </body>
115 
116 
117 </html>

猜你喜欢

转载自www.cnblogs.com/zwz178/p/9091075.html