温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot中如何实现文件上传下载

发布时间:2021-07-08 10:23:28 来源:亿速云 阅读:219 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关springboot中如何实现文件上传下载,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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));
 }
}

关于“springboot中如何实现文件上传下载”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI