jquery ajax+spring mvc上传文件

简介: jquery ajax+spring mvc上传文件

导入commons-fileupload-1.2.2.jar和commons-io-2.4.jar及spring的一些jar包

创建上传处理类UploadAction

package com.mysite.test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Controller
public class UploadAction {
  private static final Logger logger = LoggerFactory.getLogger(UploadAction.class);
  private final static int maxSize = 209715200;// 1024*1024*200 (200M)
  private String filePath="/uploads/";
  @RequestMapping(value = "/upload.do")
  public void fileUpload(HttpServletRequest request, HttpServletResponse response) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    multipartResolver.setDefaultEncoding("UTF-8");
    if (multipartResolver.isMultipart(request)) {
      StringBuffer result = new StringBuffer();
      long startTime = System.currentTimeMillis(); // 获取开始时间
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      Iterator<String> ite = multiRequest.getFileNames();
      response.setCharacterEncoding("UTF-8");
      PrintWriter writer = null;
      try {
        writer = response.getWriter();
        while (ite.hasNext()) {
          MultipartFile file = multiRequest.getFile(ite.next());
          if (file.getSize() > maxSize) {
            result.append("文件[" + file.getOriginalFilename() + "]的大小超过限制(200M)").append("\r\n");
            writer.print(result);
            writer.flush();
            return;
          }
          if (file != null) {
            try {
              File serverPath = new File(filePath);
              if (!serverPath.exists()) {
                logger.warn("The path of server save file is not exists!");
                serverPath.mkdirs();
              }
              if (!serverPath.isDirectory()) {
                logger.warn("The path of server save file is not directory!");
                return;
              }
              if (!serverPath.canWrite() || !serverPath.canRead()) {
                logger.warn("The path of server save file cannot write or cannot read!");
                serverPath.setReadable(true);
                serverPath.setWritable(true);
              }
              File localFile = new File(filePath + file.getOriginalFilename());
              if (localFile.isFile() && localFile.exists()) {
                String name = localFile.getName();
                String oldName = name.substring(0, name.lastIndexOf(".")) + "_" + System.currentTimeMillis() + "_old" + name.substring(name.lastIndexOf("."));
                FileUtils.copyFile(localFile, new File(filePath + oldName));
                FileUtils.forceDelete(localFile);
              }
              file.transferTo(localFile); // 将上传文件写到服务器上指定的文件
              long endTime = System.currentTimeMillis(); // 获取结束时间
              logger.info("upload file success!expend {} ms", (endTime - startTime));
              String filePath = localFile.getAbsolutePath();
              logger.info("the file save to:{}", filePath);
              result.append("The file [").append(file.getOriginalFilename()).append("] upload success!\n");
            } catch (IOException e) {
              logger.error("has a error:{}", e);
            }
          }
        }
        writer.print(result);
        writer.flush();
      } catch (IOException e1) {
        e1.printStackTrace();
      } finally {
        if (writer != null) {
          writer.close();
        }
      }
    }
  }
}


在springmvc-servlet.xml配置上传属性

<!-- 文件上传解析器 -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <property name="defaultEncoding" value="utf-8"></property>  
    <property name="maxUploadSize" value="209715200"></property><!-- 最大上传文件大小 200M-->  
    <property name="maxInMemorySize" value="40960"></property>  
</bean>

jsp导入js类库,因为样式是使用的easyui,所有需要引入easyui的js及样式

<script type="text/javascript" src="${base}js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${base}js/ajaxFileUpload.js"></script>
<script type="text/javascript" src="${base}js/jquery.easyui.min.js"></script>


导入样式文件

<link rel="stylesheet" type="text/css" href="${base}css/easyui.css">
<link rel="stylesheet" type="text/css" href="${base}css/icon.css">
<link rel="stylesheet" type="text/css" href="${base}css/color.css">
<link rel="stylesheet" type="text/css" href="${base}css/demo.css">

css

.aitem {margin: 10px 0 5px 0;padding-bottom: 5px;border-bottom: 1px solid #eee;}
.aitem .item {height: 40px;line-height: 40px;vertical-align: middle;}
.aitem span {padding-right: 5px;}
.aitem .title {width: 120px;}
.aitem input[type="text"],input[type="password"],input[type="file"] {width: 200px;}
/*a  upload */
.a-upload {
text-decoration:none;
    padding: 2px 10px;
    height: 20px;
    line-height: 20px;
    position: relative;
    cursor: pointer;
    color: #777;
    background: #eee;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    display: inline-block;
    *display: inline;
    *zoom: 1
}
.a-upload  input {
    position: absolute;
    width:100%;
    right: 0;
    top: 0;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer
}
.a-upload:hover {color: #444;background: #eee;border-color: #ccc;text-decoration: none;}
#fileName{color: #444;height: 24px;line-height: 24px;overflow: hidden;display: inline-block;*display: inline;*zoom: 1}


jsp

<div id="dlg" class="easyui-dialog" data-options="buttons:'#dlg-buttons',modal:true,closed:true" style="width:450px;height:330px;">
    <form id="fm" name="fm" method="post" novalidate enctype="multipart/form-data">
        <div id="uploadfile" class="aitem" style="display:block;">
            <label><span style="color:red;">*</span>需更新的文件 (文件格式:zip,tar,jar,properties,bat,sh)</label>
            <div class="item" style="height: 45px">
                    <a href="javascript:;" class="a-upload">
                        <input type="file" name="file" id="file" οnchange="change(event);">选择文件
                    </a>
                    <span id="fileName"></span>
            </div>
            <label>文件最大不能超过200M</label>
        </div>
    </form>
</div>
<div id="dlg-buttons">
    <button class="easyui-linkbutton c6" id="confirm" style="width:80px">确定</button>
    <button class="easyui-linkbutton c5"  οnclick="closeDialog('dlg')" style="width:80px">关闭窗口</button>
</div>




编写js函数

//上传文件,点击选择文件后获取文件名&文件大小
function change(event){
    event.stopPropagation();
    var src=event.target || window.event.srcElement; //获取事件源,兼容chrome/IE
    //alert( src.value );
    //测试chrome浏览器、IE6,获取的文件名带有文件的path路径
    //下面把路径截取为文件名
    var path=src.value;
    if(!path){
        return false;
    }
    var filename=path.substring( path.lastIndexOf('\\')+1 );
    //获取文件名的后缀名(文件格式)
    var suffix=path.substring( path.lastIndexOf('.')+1 );
    //zip,tar,jar,properties,bat,sh
    if(suffix.toLowerCase()!="zip"&&suffix.toLowerCase()!="tar"&&suffix.toLowerCase()!="jar"&&suffix.toLowerCase()!="properties"
        &&suffix.toLowerCase()!="bat"&&suffix.toLowerCase()!="sh"){
        $.messager.alert("警告","只能上传以下后缀名的文件\nzip,tar,jar,properties,bat,sh");
        //$("input[name='file']").val("");
        src.value="";
        if(src.id=='file')$("#fileName").empty();
        else $("#selfFileName").empty();
        return false;
    }
    var file_size = 0;
    if ($.browser.msie) {
        var img = new Image();
        img.src = path;
        file_size = img.fileSize;
    } else {
        file_size = src.files[0].size;
    }
    var size = file_size / 1024;
    var maxSize = 200*1024;//200M
    if (size > maxSize) {
        $.messager.alert("警告","只能上传200M以下的文件");
        src.value="";
        if(src.id=='file')$("#fileName").empty();
        else $("#selfFileName").empty();
        return false;
    }
    if(src.id=='file')$("#fileName").empty().text(filename);
    else $("#selfFileName").empty().text(filename);
    return true;
};
//确认上传按钮绑定事件
$("#confirm").bind("click", function(event) {
    var file=$("input[name='file']").val();
    $.messager.confirm("确认","你确定要这次操作吗?", function (r) {
        if (r) {
            if(!file){
                $.messager.alert("警告","请选择需要上传的文件!","warning");
                return false;
            }
            var command='1';
            $.ajaxFileUpload({  
                fileElementId: 'file',  
                url: 'upload.do',  
                data : {
                    /*command : command*///传参数
                },
                dataType: 'text',
                success: function (data, status) {  
                  if (status == "success") {
                        $.messager.alert("",data);
                    }
                },  
                error: function (XMLHttpRequest, status, error) {  
                    var msg = "服务器返回消息:" + XMLHttpRequest.responseText;  
                    $.messager.alert('提示',msg);  
                },  
                complete: function (obj) {
                }  
           });
        }
    });
});




co

cor

相关文章
N..
|
29天前
|
XML JSON 前端开发
jQuery实现Ajax
jQuery实现Ajax
N..
17 1
|
1月前
|
缓存 前端开发 Java
Spring MVC 面试题及答案整理,最新面试题
Spring MVC 面试题及答案整理,最新面试题
88 0
|
1月前
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
10 0
|
1月前
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
9 0
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
25 0
|
1月前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
40 1
|
10天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
22 3
|
10天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
13 1
|
10天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
29 3
|
20天前
|
前端开发 安全 Java
使用Java Web框架:Spring MVC的全面指南
【4月更文挑战第3天】Spring MVC是Spring框架的一部分,用于构建高效、模块化的Web应用。它基于MVC模式,支持多种视图技术。核心概念包括DispatcherServlet(前端控制器)、HandlerMapping(请求映射)、Controller(处理请求)、ViewResolver(视图解析)和ModelAndView(模型和视图容器)。开发流程涉及配置DispatcherServlet、定义Controller、创建View、处理数据、绑定模型和异常处理。
使用Java Web框架:Spring MVC的全面指南