sprijngBoot 2.x版本不需要添加依赖包,soringBoot以及集成好了
一: 上传文件 controller接受层
@PostMapping(value = "/fileUpload")public String fileUpload(@RequestParam(value = "file") MultipartFile file, ModelMap model, HttpServletRequest request) { if (file.isEmpty()) { System.out.println("文件为空空"); } String fileName = updateFile(request, file); model.put("fileName",fileName); return "update";} /***上传到服务器的方法*/
private String updateFile(HttpServletRequest request,MultipartFile files) { MultipartFile file = files; if (!file.isEmpty()){ try { // 保存的文件路径(如果用的是Tomcat服务器,文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中 // ) String filePath = request.getSession().getServletContext() .getRealPath("/") + "upload/" + file.getOriginalFilename(); File saveDir = new File(filePath); if (!saveDir.getParentFile().exists()){ saveDir.getParentFile().mkdirs(); } // 转存文件 保存到服务器地址上,路径在filePath file.transferTo(saveDir); /**请求图片服务器 返回字符串 * */ //得到图片全名 String originalFilename = file.getOriginalFilename(); int i1 = originalFilename.indexOf("."); String suffix = ""; if (i1 != 0){ suffix = originalFilename.substring(i1+1); }else { suffix = "jpg"; } // String fileId = fileService.uploadWithGroup(// FileCopyUtils.copyToByteArray(saveDir), FastDfsGroup.PRI_FILE, suffix); String absolutePath = saveDir.getAbsolutePath(); String canonicalPath = saveDir.getCanonicalPath(); System.out.println(absolutePath+"---"+canonicalPath); //absolutePath是文件的绝对路径,下面jsp中,预览头像时,需要回传到getUserLogo 接口中 return absolutePath; } catch (Exception e) { e.printStackTrace(); } }return null; } 二: jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Title</title></head><body><form action="/recruit/hr/fileUpload" method="post" enctype="multipart/form-data"> <label>上传图片</label> <input type="file" name="file"/> <input type="submit" value="上传"/></form><p>图片:</p><img src="/recruit/hr/getUserLogo?path=${fileName}" style="width: 73px;height: 73px"/></body></html> 三:头像预览接口
/** * 获取头像 * */@RequestMapping("/getUserLogo")public void getUserLogo(HttpServletRequest request, HttpServletResponse response, String path) { response.setContentType("image/jpeg"); // 设置返回内容格式 File file = new File(path); // 括号里参数为文件图片路径 if (file.exists()) { // 如果文件存在 InputStream in; try { in = new FileInputStream(file); OutputStream os = response.getOutputStream(); // 创建输出流 byte[] b = new byte[1024]; while (in.read(b) != -1) { os.write(b); } in.close(); os.flush(); os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
原文地址:https://www.cnblogs.com/quzhongren/p/11057809.html
时间: 2024-10-07 08:52:27