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

相关文章
|
27天前
|
存储 前端开发 Java
如何使用 Spring 上传文件:全面指南
如何使用 Spring 上传文件:全面指南
49 1
|
2月前
|
前端开发 JavaScript 数据处理
JQuery 拦截请求 | Ajax 请求拦截
【10月更文挑战第4天】
131 1
|
3月前
|
JSON 前端开发 JavaScript
jQuery AJAX 方法
jQuery AJAX 方法
41 1
|
3月前
|
JSON JavaScript 前端开发
Jquery常用操作汇总,dom操作,ajax请求
本文汇总了jQuery的一些常用操作,包括DOM元素的选择、添加、移除,表单操作,以及如何使用jQuery发送Ajax请求,涵盖了GET、POST请求和文件上传等常见场景。
|
2月前
|
安全 算法 Java
强大!基于Spring Boot 3.3 六种策略识别上传文件类型
【10月更文挑战第1天】在Web开发中,文件上传是一个常见的功能需求。然而,如何确保上传的文件类型符合预期,防止恶意文件入侵,是开发者必须面对的挑战。本文将围绕“基于Spring Boot 3.3 六种策略识别上传文件类型”这一主题,分享一些工作学习中的技术干货,帮助大家提升文件上传的安全性和效率。
90 0
|
3月前
|
JSON 前端开发 JavaScript
jQuery AJAX 方法
jQuery AJAX 方法
27 1
|
3月前
|
Java API 开发者
【已解决】Spring Cloud Feign 上传文件,提示:the request was rejected because no multipart boundary was found的问题
【已解决】Spring Cloud Feign 上传文件,提示:the request was rejected because no multipart boundary was found的问题
721 0
|
4月前
|
Java 开发工具 Spring
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
|
4月前
|
XML JSON 前端开发
AJAX是什么?原生语法格式?jQuery提供分装好的AJAX有什么区别?
AJAX是什么?原生语法格式?jQuery提供分装好的AJAX有什么区别?
35 0
|
XML JSON 缓存
JQuery中$.ajax()方法参数详解
JQuery中$.ajax()方法参数详解
85 2