1..文件上传
在springmvc.xml中配置文件上传解析器
<!-- 上传图片配置实现类,id必须为这个 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传图片的大小 B 5M 1*1024*1024*5--> <property name="maxUploadSize" value="5000000"/> </bean>
2. jsp页面修改(类似于struts2)
3.上传处理(也可以用普通servlet的io流的方式直接处理,多文件上传类似于struts2,数组方式)
方法一:
@RequestMapping("updateItem")
public String updateItemById(Item item, MultipartFile pictureFile) throws Exception {
// 图片上传
// 设置图片名称,不能重复,可以使用uuid
String picName = UUID.randomUUID().toString();
// 获取文件名
String oriName = pictureFile.getOriginalFilename();
// 获取图片后缀
String extName = oriName.substring(oriName.lastIndexOf("."));
// 开始上传
pictureFile.transferTo(new File("C:/upload/image/" + picName + extName));
// 设置图片名到商品中
item.setPic(picName + extName);
// ---------------------------------------------
// 更新商品
this.itemService.updateItemById(item);
return "forward:/itemEdit.action";
}
方法二:
// public ModelAndView updateItemById(Items items){ @RequestMapping(value = "/updateitem.action") public String updateItem(QueryVo vo, MultipartFile pictureFile) throws Exception { // 产生32位随机数并去掉- String name = UUID.randomUUID().toString().replaceAll("-", ""); // jpg 获取文件拓展名 String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename()); // 保存文件,用UUID产生的唯一名字保存 pictureFile.transferTo(new File("F:\\upload\\" + name + "." + ext)); vo.getItems().setPic(name + "." + ext); // 修改 vo.getItems().setCreatetime(new Date()); itemService.updateItemsById(vo.getItems()); // ModelAndView mav = new ModelAndView(); // mav.setViewName("success"); return "redirect:/itemEdit.action?id=" + vo.getItems().getId(); }
----------------------------------------------------------------------------------------文件下载处理(引用另一篇博客的)--------------------------------------------------------------------------------------
@RequestMapping("file") @Controller public class FileController { /** * 文件上传功能 * @param file * @return * @throws IOException */ @RequestMapping(value="/upload",method=RequestMethod.POST) @ResponseBody public String upload(MultipartFile file,HttpServletRequest request) throws IOException{ String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); File dir = new File(path,fileName); if(!dir.exists()){ dir.mkdirs(); } //MultipartFile自带的解析方法 file.transferTo(dir); return "ok!"; } /** * 文件下载功能 * @param request * @param response * @throws Exception */ @RequestMapping("/down") public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{ //模拟文件,myfile.txt为需要下载的文件 String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt"; //获取输入流 InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //假如以中文名下载的话 String filename = "下载文件.txt"; //转码,免得文件名中文乱码 filename = URLEncoder.encode(filename,"UTF-8"); //设置文件下载头 response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); } }
例如:自己写的一个查询数据写入到excel中并提供下载的方法:
package cn.xm.jwxt.controller.trainScheme; import cn.xm.jwxt.service.trainScheme.CourseBaseInfoService; import cn.xm.jwxt.utils.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.reflect.Method; import java.net.URLEncoder; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; /** * @Author: qlq * @Description 导出课程信息到Excel中 * @Date: 10:11 2018/4/29 */ @Controller public class ExtCourseExcel { @Autowired private CourseBaseInfoService courseBaseInfoService; private Logger logger = Logger.getLogger(ExtCourseExcel.class); //1.先从缓存中取数据,看能取到取不到 //2.写入excel到本地 //3.打开流提供下载 //1.查询数据 public List<Map<String, Object>> getCourseBaseInfosByCondition(@RequestParam Map<String, Object> condition) { List<Map<String, Object>> datas = null; try { datas = courseBaseInfoService.getCourseBaseInfosByCondition(condition); } catch (SQLException e) { logger.error("导出课程信息的时候查询数据库出错",e); } return datas; } //2.写文件到excel中 /** * 写数据到本地磁盘 * @param datas 课程数据 * @param fileQualifyName 文件全路径(比如C:/USER/XXX.excel) */ public void writeCourse2LocalExcel(List<Map<String,Object>> datas,String fileQualifyName){ String[] title = { "序号", "课程编号", "课程平台","课程性质","中文名称","英文名称","学分/学时", "周学时分配","计分方式" }; //2.1写入表头信息 // 创建一个工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个工作表sheet HSSFSheet sheet = workbook.createSheet(); // 设置列宽 this.setColumnWidth(sheet, 9); // 创建第一行 HSSFRow row = sheet.createRow(0); // 创建一个单元格 HSSFCell cell = null; // 创建表头 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); // 设置样式 HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置字体居中 // 设置字体 HSSFFont font = workbook.createFont(); font.setFontName("宋体"); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字体加粗 // font.setFontHeight((short)12); font.setFontHeightInPoints((short) 13); cellStyle.setFont(font); cell.setCellStyle(cellStyle); cell.setCellValue(title[i]); } // 2.2写入数据 // 从第二行开始追加数据 for (int i = 1, length_1 = (datas.size() + 1); i < length_1; i++) { // 创建第i行 HSSFRow nextRow = sheet.createRow(i); // 设置样式 HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置字体居中 // 获取数据(一条数据) Map<String, Object> course = datas.get(i - 1); for (int j = 0; j < 9; j++) { HSSFCell cell2 = nextRow.createCell(j); cell2.setCellStyle(cellStyle); if (j == 0) { cell2.setCellValue(i);//第一列是序号 continue; } if (j == 1) { cell2.setCellValue(course.get("courseNum").toString());//课程编号 continue; } if (j == 2) { cell2.setCellValue(course.get("coursePlatform").toString());//课程平台 continue; } if (j == 3) { cell2.setCellValue(course.get("courseNature").toString());//课程性质 continue; } if (j == 4) { cell2.setCellValue(course.get("courseNameCN").toString());//中文名称 continue; } if (j == 5) { cell2.setCellValue(course.get("courseNameEN").toString());//英文名称 continue; } if (j == 6) { cell2.setCellValue(course.get("credit").toString()+"/"+course.get("courseHour").toString());//学分/学时 continue; } if (j == 7) { cell2.setCellValue(course.get("weeklyHour").toString());//周学时 continue; } if (j == 8) { cell2.setCellValue(course.get("scoringWay").toString());//计分方式 continue; } } } // 创建一个文件 File file = new File(fileQualifyName); // 获取文件的父文件夹并删除文件夹下面的文件 File parentFile = file.getParentFile(); // 获取父文件夹下面的所有文件 File[] listFiles = parentFile.listFiles(); if (parentFile != null && parentFile.isDirectory()) { for (File fi : listFiles) { // 删除文件 fi.delete(); } } // 如果存在就删除 if (file.exists()) { file.delete(); } try { file.createNewFile(); // 打开文件流并写入文件 FileOutputStream outputStream = org.apache.commons.io.FileUtils.openOutputStream(file); workbook.write(outputStream); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 设置列宽的函数 * @param sheet 对哪个sheet进行设置, * @param colNum */ private void setColumnWidth(HSSFSheet sheet, int colNum) { for (int i = 0; i < colNum; i++) { int v = 0; v = Math.round(Float.parseFloat("15.0") * 37F); v = Math.round(Float.parseFloat("20.0") * 267.5F); sheet.setColumnWidth(i, v); } } //3.打开流提供下载 @RequestMapping("/downCourses") public void down(HttpServletRequest request, HttpServletResponse response,@RequestParam Map condition){ //1.查询数据 List<Map<String, Object>> datas = this.getCourseBaseInfosByCondition(condition); //2.写入excel String dir = ResourcesUtil.getValue("path","courseExcelFile"); String fileName = DefaultValue.COURSE_DEFAULT_FILENAME; String fileQualifyName = dir + fileName;//生成的excel名字 this.writeCourse2LocalExcel(datas,fileQualifyName);//写入数据(生成文件) //3.打开流提供下载 //获取输入流 try { InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileQualifyName))); fileName = URLEncoder.encode(fileName,"UTF-8"); //设置文件下载头 response.addHeader("Content-Disposition", "attachment;filename=" + fileName); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); } catch (Exception e) { logger.error("下载课程信息出错!",e); } } }