第一步:在applicationContext.xml中添加支持<!-- 支持文件上传 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
第二步: /** * 上传文件 * * @param file * @param request * @param model * @return */ @RequestMapping(value = "/upload") public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) { //如果文件为空则返回uploadTxt.jsp if (file.isEmpty()) { return "uploadTxt"; } System.out.println("start upload file"); String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename();// //如果文件格式不是txt,返回uploadTxt.jsp// if (!fileName.endsWith("txt")) {// return "uploadTxt";// } System.out.println("fileName====> " + fileName);// String fileName = new Date().getTime()+".jpg"; System.out.println("file path:" + path); File targetFile = new File(path, fileName); if (!targetFile.exists()) { //创建目录 targetFile.mkdirs(); } try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName); return "forward:/list"; }
/** * 获取上传路径上的所有文件 * * @param request * @return */ @RequestMapping("/listFile") public ModelAndView list(HttpServletRequest request) { String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; ModelAndView modelAndView = new ModelAndView(); File uploadDest = new File(filePath); String[] fileNames = uploadDest.list();// for (int i = 0; i < fileNames.length; i++) {// //输出所有文件名// System.out.println(fileNames[i]);// } String jsonString = JSON.toJSONString(fileNames); modelAndView.addObject("fileNamesJsonString", jsonString); System.out.println(jsonString); modelAndView.setViewName("listFile"); return modelAndView; }
/** * download File * * @param request * @param fileName * @return * @throws IOException */@RequestMapping("/download")public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("fileName") String fileName) throws IOException { String path = request.getServletContext().getRealPath("/upload/"); File dwFile = new File(path + File.separator + fileName); HttpHeaders headers = new HttpHeaders(); //下载显示的中文名,解决中文名称乱码问题 String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); //application/octet-stream:二进制流数据 headers.setContentDispositionFormData("attachment", downloadFileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(dwFile), headers, HttpStatus.CREATED);}
时间: 2024-10-08 11:18:40