springboot 中文件上传下载实例代码
SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,SpringBoot致力于在蓬勃发展的快速应用开发领域(rapidapplicationdevelopment)成为领导者。
SpringBoot特点
1.创建独立的Spring应用程序
2.嵌入的Tomcat,无需部署WAR文件
3.简化Maven配置
4.自动配置Spring
5.提供生产就绪型功能,如指标,健康检查和外部配置
6.绝对没有代码生成和对XML没有要求配置[
springboot实现文件上传下载实例代码如下所示:
@Controller publicclassFileUploadCtrl{ @Value("${file.upload.dir}") privateStringpath; /** *实现文件上传 **/ @RequestMapping(value="/fileUpload",method=RequestMethod.POST) @ResponseBody publicMapfileUpload(@RequestParam("fileName")MultipartFilefile){ Map map=newHashMap (); intno=0; Stringmsg="上传失败!"; if(!file.isEmpty()){ StringfileName=file.getOriginalFilename(); Filedest=newFile(path+"/"+fileName); if(!dest.getParentFile().exists()){//判断文件父目录是否存在 dest.getParentFile().mkdir(); } try{ file.transferTo(dest);//保存文件 no=1; msg="上传成功!"; }catch(IllegalStateExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } map.put("no",no); map.put("msg",msg); returnmap; } @RequestMapping( value="/fileDownload", method=RequestMethod.GET ) publicResponseEntity>getGwFileContent(@RequestParamStringfileName,@RequestParamintflag){ HttpHeadersheaders=newHttpHeaders(); headers.add("Cache-Control","no-cache,no-store,must-revalidate"); Stringfilepath=path+"/"+fileName;; InputStreamis=null; try{ headers.add("Content-Disposition",String.format("attachment;filename=\"%s\"",newString(fileName.getBytes("GBK"),"ISO8859-1"))); if(flag==0){//表示获取缩略图 Filefile=newFile(filepath); filepath=path+"/xx"+fileName; FilexxFile=newFile(filepath); if(!xxFile.exists()){//不存在就生成缩略图 Thumbnails.of(file).scale(0.25f).toFile(xxFile); } } is=newFileInputStream(newFile(filepath)); }catch(UnsupportedEncodingExceptione){ e.printStackTrace(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } headers.add("Pragma","no-cache"); headers.add("Expires","0"); returnResponseEntity .ok() .headers(headers) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(newInputStreamResource(is)); } }
总结
以上所述是小编给大家介绍的springboot中文件上传下载实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!