欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

springboot 中文件上传下载实例代码

时间:2021-08-04 08:33:26|栏目:JAVA代码|点击:

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

Spring Boot特点

1. 创建独立的Spring应用程序

2. 嵌入的Tomcat,无需部署WAR文件

3. 简化Maven配置

4. 自动配置Spring

5. 提供生产就绪型功能,如指标,健康检查和外部配置

6. 绝对没有代码生成和对XML没有要求配置[

springboot 实现文件上传下载实例代码如下所示:

@Controller
public class FileUploadCtrl {
 @Value("${file.upload.dir}")
 private String path;
 /**
  * 实现文件上传
  * */
 @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
 @ResponseBody
 public Map<String,Object> fileUpload(@RequestParam("fileName") MultipartFile file){
  Map<String,Object> map = new HashMap<String, Object>();
  int no = 0;
  String msg = "上传失败!";
  if(!file.isEmpty()){
   String fileName = file.getOriginalFilename();
   File dest = new File(path + "/" + fileName);
   if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
    dest.getParentFile().mkdir();
   }
   try {
    file.transferTo(dest); //保存文件
    no = 1;
    msg = "上传成功!";
   } catch (IllegalStateException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  map.put("no",no);
  map.put("msg", msg);
  return map;
 }
 @RequestMapping(
   value = "/fileDownload",
   method = RequestMethod.GET
 )
 public ResponseEntity<?> getGwFileContent(@RequestParam String fileName,@RequestParam int flag) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  String filepath = path+"/"+fileName;;
  InputStream is = null;
  try {
   headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(fileName.getBytes("GBK"), "ISO8859-1")));
   if(flag==0){//表示获取缩略图
    File file = new File(filepath);
    filepath = path+"/xx"+fileName;
    File xxFile = new File(filepath);
    if(!xxFile.exists()){//不存在就生成缩略图
     Thumbnails.of(file).scale(0.25f).toFile(xxFile);
    }
   }
   is = new FileInputStream(new File(filepath));
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  headers.add("Pragma", "no-cache");
  headers.add("Expires", "0");
  return ResponseEntity
    .ok()
    .headers(headers)
    .contentType(MediaType.parseMediaType("application/octet-stream"))
    .body(new InputStreamResource(is));
 }
}

总结

上一篇:浅谈java面向对象(类,封装,this,构造方法)

栏    目:JAVA代码

下一篇:java经典问题:连个字符串互为回环变位

本文标题:springboot 中文件上传下载实例代码

本文地址:http://www.codeinn.net/misctech/164081.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有