/** * @author admin * @描述 * @创建人 admin * @创建时间 2022/6/8 16:24 **/ @RestController @RequestMapping("file") public class FileController { @Value("${file.upload.windowUrl}") private String windowUrl; @Value("${file.upload.linuxUrl}") private String linuxUrl; @RequestMapping("/upload") public String httpUpload(@RequestParam("files") MultipartFile[] files){ JSONObject object=new JSONObject(); for(int i=0;i<files.length;i++){ String fileName = files[i].getOriginalFilename(); // 文件名 File dest = null; if("window".equals(checkSystem())){ dest =new File(windowUrl + fileName); } if("linux".equals(checkSystem())){ dest = new File(linuxUrl + fileName); } if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { files[i].transferTo(dest); } catch (Exception e) { object.put("success",2); object.put("result","程序错误,请从新上传"); return object.toString(); } } object.put("success",1); object.put("result","文件上传成功"); return object.toString(); } @RequestMapping("/download") public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){ File file = null; if("window".equals(checkSystem())){ file =new File(windowUrl + fileName); } if("linux".equals(checkSystem())){ file = new File(linuxUrl + fileName); } if(!file.exists()){ return "下载文件不存在"; } response.reset(); response.setContentType("application/octet-stream"); response.setCharacterEncoding("utf-8"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment;filename=" + fileName ); try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) { byte[] buff = new byte[1024]; OutputStream os = response.getOutputStream(); int i = 0; while ((i = bis.read(buff)) != -1) { os.write(buff, 0, i); os.flush(); } } catch (IOException e) { return "下载失败"; } return "下载成功"; } private String checkSystem(){ String rt=""; String info = System.getProperty("os.name"); if (info != null && info.toLowerCase().startsWith("window")) { //window系统 rt = "window"; } if (info != null && info.toLowerCase().startsWith("linux")) { //Linux操作系统 rt = "linux"; } return rt; } }
application.yml
file:
upload:
windowUrl: D:TestFile/
linuxUrl: /home/TestFile/