public class FileController { /** * 文件下载路径 */ String filePath=“file"; private static final Logger logger = LoggerFactory.getLogger(FileController.class); /** * 文件上传相关代码 * * @param file * @return */ @RequestMapping(value = "upload") public String upload(@RequestParam("test") MultipartFile file) { if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename(); logger.info("上传的文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上传的后缀名为:" + suffixName); // 文件上传后的路径 String projectPath = new File("").getAbsolutePath(); System.out.println("文件上传后的路径"+projectPath); // 解决中文问题,liunx下中文路径,图片显示问题 // fileName = UUID.randomUUID() + suffixName; //File.separator获取不同操作系统下的分隔符。 File dest = new File(projectPath + File.separator + filePath + File.separator + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上传成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上传失败"; } /** * 文件下载相关代码 * * @param request * @param response * @return */ @RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) { //文件名 String fileName = "反档入参.doc"; System.out.println("我进来了吗"); if (fileName != null) { //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录 // String realPath = new File("").getAbsolutePath() + File.separator + filePath; System.out.println("enenen"+new File("").getAbsolutePath()); System.out.println(File.separator); System.out.println(filePath); // System.out.println("这个路劲"+realPath); String realPath="D:\\personalprogress\\upload\\SpringUploadDownload-master\\file"; File file = new File(realPath, fileName); if (file.exists()) { FileInputStream fis = null; BufferedInputStream bis = null; try { response.setContentType("application/force-download"); // 设置文件名 支持中文 fileName = URLEncoder.encode(fileName, "UTF-8"); response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } }
springboot实现文件的上传和下载
最新推荐文章于 2024-09-08 11:35:24 发布