struts2+ajaxfileupload完成单图片无刷新上传

2 篇文章 0 订阅
1 篇文章 0 订阅

一、项目结构图

二、web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置前端控制器 -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app> 

三、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="json-default">
        <action name="upload" 
        	    class="com.crazyjiang.action.UploadAction">
            <result name="success" type="json">
            	<param name="contentType">text/html</param>
            </result>
        </action>
    </package>
    
</struts>

四、action

package com.crazyjiang.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import com.opensymphony.xwork2.ActionContext;

public class UploadAction {
	private File image;//接收的图�?
	private String imageFileName;//图片名称必须写,否则接收不成�?
	private String imageContentType;//图片类型必须写,否则接收不成�?
	private String message="成功";//json字符串,返回到上传页�?

	public String execute(){
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
      //System.out.println("realpath: "+realpath);
        if (image != null) {
                //File savefile = new File(new File(realpath), imageFileName);
        	  File savefile= new File(realpath+File.separator+imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            try {
				FileUtils.copyFile(image, savefile);
			} catch (IOException e) {
				message="上传失败";
				e.printStackTrace();
			}
        }
        return "success";
    }

	//省略get、set
	
	
}

五、jsp

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

<html>
    <head>
        <title>文件上传</title>
        
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script type="text/javascript" src="js/jquery-1.4.3.js"></script>
        <script type="text/javascript" src="js/ajaxfileupload.js"></script>
   	    <script type="text/javascript">
    	  $(function(){
    	 	$('#submit').click(function(){
    	 		$.ajaxFileUpload(
    	 		{
    	 			url:'upload/upload.do',//处理请求的Action对应的url
    	 			secureuri:false,//安全传输,一般选false
    	 			fileElementId:'image',//上传文件的id
    	 			dataType:'json',//服务器返回的数据类型:一般选json
    	 			success:function(data,status){//服务器返回数据成功的回调函数
    	 						$('#filespan').text(data.message);
    	 					},
    	 			error:function(data,status,e){//服务器返回数据失败的回调函数
    	 						alert(e);
    	 				  }
    	 		 })
    	 	})
    	}); 
    	</script>
    </head>

    <body>
    	<!-- 上传文件的form必须设置enctype为该类型且method为post -->
        <form action="" 
              enctype="multipart/form-data" 
              method="post">
              ajax测试框,请在上传图片前在文本框中随意输入内容:<br/>
             <input id="test"/><br/><br/>
           	    文件上传框:<br/>
             <input type="file" name="image" id="image"/>
	   		 <input type="button" id="submit" value="submit" /><br/>
	    	 <span id="filespan">用于显示服务器返回json内容</span>
        </form>
        <br/>
    </body>
</html>

六、运行效果

      1.jsp页面效果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值