JQuery的AJAX与Spring MVC实现异步文件上传

时间:2023-01-23 21:55:35

更多文章请进入:我的开源网

需要:

ajaxfileupload.js包

jquery包

这里还用到了jquery easy ui


action代码:

package com.cjh.action;


import java.io.File;
import java.util.UUID;


import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Controller
public class FileUpload {


/**
* 文件上传
* @param file
* @return
*/
@RequestMapping(value="/fileUpload",method=RequestMethod.POST)
@ResponseBody
public String fileUpload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request){
/**判断文件是否为空,空直接返回上传错误**/
if(!file.isEmpty()){
/**获取本地文件存储目录**/
String path = request.getSession().getServletContext().getRealPath("/fileupload/");
/**获得文件名**/
String fileName = file.getOriginalFilename();
/**获得文件后缀名**/
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
/**拼接文件路径,以UUID生成文件名**/
String filePath = path + File.separator + UUID.randomUUID().toString()+ suffix;
/**创建一个要保存的新文件**/
File saveFile = new File(filePath);

try{
/**将文件写入到新文件中**/
file.getFileItem().write(saveFile);

}catch(Exception e ){
e.printStackTrace();
return "{\"code\":\"-1\"}";
}
return "{\"code\":\"1\"}";


}else{
return "{\"code\":\"-1\"}";
}

}


}



fileupload.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">


<title>My JSP 'main2.jsp' starting page</title>


<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


<!-- 导入对应的样式和js -->
<jsp:include page="../manage/comm/comm-index.jsp"></jsp:include>
<script type="text/javascript" src="manage/js/ajaxfileupload.js"></script>


<!-- 执行上传文件操作的函数 -->
<script type="text/javascript">
          function ajaxFileUpload(){
               $.ajaxFileUpload(
                   {
                url:'<%=path %>/fileUpload.do', //需要链接到服务器地址
                secureuri:false,
                fileElementId:'file', //文件选择框的id属性
                dataType: 'json',  //服务器返回的格式类型
                success: function (data, status) //成功
                {      
                    var json =  eval("("+data+")");//解析返回的json
                    var code = json.code;
                    if(code==1){
                      $.messager.alert("提示","上传成功!","info");
                    }else{
                      $.messager.alert("提示","上传失败!","warning");
                    }
                     
                    
                },
                error: function (data, status, e) //异常
                {
                   $.messager.alert("提示","出错了,请重新上传!","error");
                }
            }
                   
               );
            return false;  
          }
      </script>
</head>


<body>
   <table >
    <tr height="50px">
     <td>
<form method="post" action=""
enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<a href="javascript:void(0)"onclick="return ajaxFileUpload()" class="easyui-linkbutton" iconCls="icon-ok">上传</a>
</form>
 </td>
</tr>
</table>


</body>
</html>