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

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

需要:

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)"οnclick="return ajaxFileUpload()" class="easyui-linkbutton" iconCls="icon-ok">上传</a>
</form>
 </td>
</tr>
</table>


</body>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
实现三级联动的基本思路是通过Ajax技术实现异步请求后端数据,然后动态生成页面元素实现级联效果。下面是一个Spring MVC+JSP实现三级联动的示例代码: 1. 前端JSP页面 ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>三级联动示例</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ // 加载省份列表 $.ajax({ url: "${pageContext.request.contextPath}/province", type: "GET", success: function(data){ var provinceList = JSON.parse(data); var html = ""; for(var i=0; i<provinceList.length; i++){ html += "<option value='"+provinceList[i].id+"'>"+provinceList[i].name+"</option>"; } $("#province").html(html); } }); // 根据省份id加载城市列表 $("#province").change(function(){ var provinceId = $(this).val(); $.ajax({ url: "${pageContext.request.contextPath}/city/"+provinceId, type: "GET", success: function(data){ var cityList = JSON.parse(data); var html = ""; for(var i=0; i<cityList.length; i++){ html += "<option value='"+cityList[i].id+"'>"+cityList[i].name+"</option>"; } $("#city").html(html); } }); }); // 根据城市id加载区县列表 $("#city").change(function(){ var cityId = $(this).val(); $.ajax({ url: "${pageContext.request.contextPath}/district/"+cityId, type: "GET", success: function(data){ var districtList = JSON.parse(data); var html = ""; for(var i=0; i<districtList.length; i++){ html += "<option value='"+districtList[i].id+"'>"+districtList[i].name+"</option>"; } $("#district").html(html); } }); }); }); </script> </head> <body> <select id="province"> <option value="">请选择省份</option> </select> <select id="city"> <option value="">请选择城市</option> </select> <select id="district"> <option value="">请选择区县</option> </select> </body> </html> ``` 2. 后端Controller代码 ```java @Controller public class RegionController { @Autowired private RegionService regionService; @RequestMapping(value="/province", method=RequestMethod.GET) @ResponseBody public String getProvinceList(){ List<Province> provinceList = regionService.getProvinceList(); return JSON.toJSONString(provinceList); } @RequestMapping(value="/city/{provinceId}", method=RequestMethod.GET) @ResponseBody public String getCityList(@PathVariable("provinceId") String provinceId){ List<City> cityList = regionService.getCityList(provinceId); return JSON.toJSONString(cityList); } @RequestMapping(value="/district/{cityId}", method=RequestMethod.GET) @ResponseBody public String getDistrictList(@PathVariable("cityId") String cityId){ List<District> districtList = regionService.getDistrictList(cityId); return JSON.toJSONString(districtList); } } ``` 3. Service层代码 ```java @Service public class RegionServiceImpl implements RegionService { @Autowired private RegionDao regionDao; @Override public List<Province> getProvinceList() { return regionDao.getProvinceList(); } @Override public List<City> getCityList(String provinceId) { return regionDao.getCityList(provinceId); } @Override public List<District> getDistrictList(String cityId) { return regionDao.getDistrictList(cityId); } } ``` 4. DAO层代码 ```java @Repository public class RegionDaoImpl implements RegionDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Province> getProvinceList() { String sql = "select province_id, province_name from tb_province"; List<Province> provinceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Province>(Province.class)); return provinceList; } @Override public List<City> getCityList(String provinceId) { String sql = "select city_id, city_name from tb_city where province_id=?"; List<City> cityList = jdbcTemplate.query(sql, new Object[]{provinceId}, new BeanPropertyRowMapper<City>(City.class)); return cityList; } @Override public List<District> getDistrictList(String cityId) { String sql = "select district_id, district_name from tb_district where city_id=?"; List<District> districtList = jdbcTemplate.query(sql, new Object[]{cityId}, new BeanPropertyRowMapper<District>(District.class)); return districtList; } } ``` 其中Province、City和District是数据实体类,包含id和name两个属性。以上代码只是一个简单示例,实际项目中需要根据具体需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

河马开源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值