easyUI利用ajax上传文件后台
后台代码
controller
@RequestMapping("/excelUploadItemList") @ResponseBody public CommonResponse excelUploadItemList(@RequestParam MultipartFile upFile, HttpServletRequest request, HttpServletResponse response) { String result = null; try { if (request instanceof MultipartHttpServletRequest) { String filename = upFile.getOriginalFilename(); String tempPath; logger.info("生成路径"); //String fsRoot = ConfigPool.getConfigValue("storage.fs.root"); String fsRoot = "C:\\TempFile"; tempPath = fsRoot + File.separator + "temp" + File.separator + filename; File f = new File(fsRoot + File.separator + "temp"); if (!f.exists()) { f.mkdirs(); } File newFile = new File(tempPath); upFile.transferTo(newFile); if (ExcelPublic.checkArray(tempPath)) { // 第一行有值 // 读取第一行的值 logger.info("开始读取文件!"); ArrayList<String> al = new ArrayList<String>(); // 读取第一行,标题字段行 al = ExcelPublic.readExcelFirstline(tempPath); // [商品ID, 商品标题, 商品卖点, 商品价格] System.out.println("al:" + al); // 读取excel中所有内容 String[][] content = ExcelPublic.dyadicArray(tempPath, 1, 0); // [[商品ID,商品标题,商品卖点,商品价格],[123456,K20Pro,大内存,2799],[234567,iPhoneSE,新机,3299]] System.out.println("content:" + content); logger.info("读取文件后获取列"); Map<String, Integer> locationMap = new HashMap<String, Integer>(); // 存放需要插入的数据的位置 String[] finalFieldArr = { "商品ID", "商品标题", "商品卖点", "商品价格"}; // 读取标题字段及其所在列位置 locationMap = readLocation(tempPath, finalFieldArr); // {商品标题=1, 商品卖点=2, 商品ID=0, 商品价格=3} System.out.println("locationMap:" + locationMap); if (locationMap.containsValue(-1)) { result = "表头不正确,正确表头为:" + Arrays.asList(finalFieldArr); throw new Exception(result); } logger.info("导入实际文件中"); result = this.itemService.excelUploadItemList(al, content, locationMap); } } } catch (Exception e) { // 失败 result = e.toString(); e.printStackTrace(); CommonResponse commonresponse = new CommonResponse(); commonresponse.setSuccFlag(false); commonresponse.setMsg(result); return commonresponse; } // 成功 CommonResponse commonresponse = new CommonResponse(); commonresponse.setSuccFlag(true); response.setContentType("text/plain; charset=UTF-8"); return commonresponse; }
service
@Override public String excelUploadItemList(ArrayList<String> al, String[][] content, Map<String, Integer> locationMap) { Map<String, String[]> itemMap = new HashMap<>(); for (int i = 1; i < content.length; i++) { String itemId = content[i][locationMap.get("商品ID")]; itemMap.put(itemId, content[i]); } // 生成时间 String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); // sql String sql = "insert into tb_item (id, title, sell_point, price, num , cid, status, created, updated) values(?, ?, ?, ?, 500, 560, 1, '" + date +"','" + date + "')"; // 参数 List<Object[]> batchArgs = new ArrayList<Object[]>(); // 封装参数 for (int i = 1; i < content.length; i++) { String[] rowData = content[i]; Object[] batchArg = new Object[]{rowData[0], rowData[1], rowData[2], rowData[3]}; batchArgs.add(batchArg); } String result = ""; try { jdbcTemplate.batchUpdate(sql, batchArgs); result = "success"; } catch (DataAccessException e) { e.printStackTrace(); } return result; }
CommonResponse.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * CommonResponse.java * Created at 2015-04-14 * Created by zhaozhong */ package com.alphajuns.ssm.util; /** * <p>ClassName: BaseObject</p> * <p>Description: 通用的response对象,主要提供给rest api返回值</p> * <p>Date: Apr 14, 2015</p> */ public class CommonResponse extends BaseObject { /** * */ private static final long serialVersionUID = 5382262170831616150L; /** * 0: SUCCESS; 1: FAILED */ private int succFlag = 0; /** * */ private String msg = ""; /** * 普通数据 */ private Object data; /** * 扩展数据 */ private Object dataExt; /** * */ private Object rows = ""; /** * */ private long total = 0; /** * success */ public static final int SUCCESS = 0; /** * fail */ public static final int FAIL = 1; public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public int getSuccFlag() { return this.succFlag; } public void setSuccFlag(int succFlag) { this.succFlag = succFlag; } public void setSuccFlag(boolean succFlag){ if(succFlag){ this.succFlag = 0; }else{ this.succFlag = 1; } } public Object getData() { return this.data; } public void setData(Object data) { this.data = data; } /** * <p>Description: getRows</p> * @return the rows */ public Object getRows() { return this.rows; } /** * <p>Description: setRows</p> * @param rows the rows to set */ public void setRows(Object rows) { this.rows = rows; } /** * <p>Description: getTotal</p> * @return the total */ public long getTotal() { return this.total; } /** * <p>Description: setTotal</p> * @param total the total to set */ public void setTotal(long total) { this.total = total; } /** * <p>Description: getDataExt</p> * @param data ext to get */ public Object getDataExt() { return dataExt; } /** * <p>Description: setDataExt</p> * @param data ext to set */ public void setDataExt(Object dataExt) { this.dataExt = dataExt; } }
BaseObj.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * BaseObject.java * Created at 2015-04-14 * Created by zhaozhong */ package com.alphajuns.ssm.util; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p>ClassName: BaseObject</p> * <p>Date: Apr 14, 2015</p> */ public class BaseObject implements Serializable { /** * */ private static final long serialVersionUID = 3230642693256329460L; /** * */ private long createBy; /** * */ private String createAt; /** * */ private long lastModifiedBy; /** * */ private String lastModifiedAt; /** * toString * @return String */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } /** * equals * @param o o * @return boolean */ @Override public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } /** * hashCode * @return int */ @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * <p>Description: getCreateBy</p> * @return the createBy */ public long getCreateBy() { return this.createBy; } /** * <p>Description: setCreateBy</p> * @param createBy the createBy to set */ public void setCreateBy(long createBy) { this.createBy = createBy; } /** * <p>Description: getCreateAt</p> * @return the createAt */ public String getCreateAt() { return this.createAt; } /** * <p>Description: setCreateAt</p> * @param createAt the createAt to set */ public void setCreateAt(String createAt) { this.createAt = createAt; } /** * <p>Description: getLastModifiedBy</p> * @return the lastModifiedBy */ public long getLastModifiedBy() { return this.lastModifiedBy; } /** * <p>Description: setLastModifiedBy</p> * @param lastModifiedBy the lastModifiedBy to set */ public void setLastModifiedBy(long lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } /** * <p>Description: getLastModifiedAt</p> * @return the lastModifiedAt */ public String getLastModifiedAt() { return this.lastModifiedAt; } /** * <p>Description: setLastModifiedAt</p> * @param lastModifiedAt the lastModifiedAt to set */ public void setLastModifiedAt(String lastModifiedAt) { this.lastModifiedAt = lastModifiedAt; } }