后台代码
/** * * @author */@Controller@RequestMapping("/user")public class UserController extends BaseController { @Autowired private UserService userService; /** * 跳转用户文件上传页面 * * @return */ @RequestMapping(value = "/uploadPage") public String uploadPage() { return "/admin/newFile"; } //上传文件 @RequestMapping(value = "/upload") public String upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request, ModelMap model) { System.out.println("开始"); // getRealPath("/") 得到的就是你tomcat下webapps下的项目根路径 String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); // String fileName = new Date().getTime()+".jpg"; System.out.println(path); File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", fileName); return "/admin/newFile"; } //下载文件 @RequestMapping("/download") public String download(String fileName, HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); try { String path = request.getSession().getServletContext().getRealPath("upload") + File.separator; String temp = request.getParameter("fileName"); InputStream inputStream = new FileInputStream(new File(path + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 这里主要关闭。 os.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } // 返回值要注意,要不然就出现下面这句错误! return null; }}