springboot实现简单的上传下载

eneity:/** * 主键 */ @Id @Column(length = 50) private String id= UUIDHelper.NewID(); /** * 上传人 */ private String siteId; /** * 文件路径 */ private String path;

controller:

/** * 文件上传 * @param siteId * @return RestResponse */ @ApiOperation(value = “文件上传”, notes = “文件上传”) @PostMapping(“/uploadFile”) public RestResponse upload(String siteId, MultipartFile file) { RestResponse restResp = new RestResponse(); if (StringUtils.isBlank(siteId)){ return restResp.setMsg(“siteId不能为空”); } try { //公共地址 String fileSpace=”F:/demo_upload”; //定义一个保存数据库的相对目录 String uploadPathDB=”/”+siteId+”/file”;// 获取文件名 String filename = file.getOriginalFilename(); if(StringUtils.isNotBlank(filename)){ //确定文件的最终上传路径 String finalFacePath=fileSpace+uploadPathDB+”/”+filename; //设置保存数据库中的目录 uploadPathDB+=(“/”+filename); //判断目录是否存在,不存在就创建 File outFile=new File(finalFacePath); if(outFile.getParentFile()!=null||!outFile.getParentFile().isDirectory()){ outFile.getParentFile().mkdirs(); } //上传 file.transferTo(outFile); //将上传的文件名保存数据库 DtoFileUpload files = new DtoFileUpload(); files.setSiteId(siteId); files.setPath(uploadPathDB); service.save(files); restResp.setRestStatus(StringUtil.isNull(outFile) ? ERestStatus.UNMATCH_RECORD : ERestStatus.SUCCESS); return restResp; } } catch (IOException e) { e.printStackTrace(); } return restResp.setMsg(“上传失败”); } /** * 文件下载 */ @ApiOperation(value = “文件下载”, notes = “文件下载”) @GetMapping(“/download”) public void download(String id, HttpServletResponse resp) throws IOException { DtoFileUpload file = service.findById(id);// String fileName=file.getSiteId(); String path=file.getPath(); String downPath=”F:/demo_upload/”+path; FileInputStream fileInputStream=new FileInputStream(downPath); ServletOutputStream outputStream = resp.getOutputStream(); IOUtils.copy(fileInputStream,outputStream); fileInputStream.close(); }

简单代码如上,可以直接套用,喜欢可以点个赞哦,谢谢

郑重声明:本文内容及图片均整理自互联网,不代表本站立场,版权归原作者所有,如有侵权请联系管理员(admin#wlmqw.com)删除。
上一篇 2022年6月17日 13:19
下一篇 2022年6月17日 13:20

相关推荐

联系我们

联系邮箱:admin#wlmqw.com
工作时间:周一至周五,10:30-18:30,节假日休息