SpringBoot进阶之文件上传(单文件上传/多文件上传)
来源:互联网 发布:java代理模式的好处 编辑:程序博客网 时间:2024/05/01 08:26
1.单文件上传
private String uploadPath="D:\\tomcat\\apache-tomcat-7.0.81-windows-x64\\apache-tomcat-7.0.81\\webapps\\img\\"; private String URL="http://127.0.0.1:8880/img/"; /** * 单个文件上传 文件上传成功后返回文件的访问路径 * @param file * @return */ @ResponseBody @RequestMapping(value = "/upload",method = RequestMethod.POST) public Msg upload(@RequestParam("file")MultipartFile file) { if(!file.isEmpty()) { File fil=new File(uploadPath+file.getOriginalFilename()); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fil)); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ResultUtil.error(200, "文件上传失败{}" + e.getMessage()); } catch (IOException e) { e.printStackTrace(); return ResultUtil.error(200, "文件上传失败{}" + e.getMessage()); } return ResultUtil.success(URL+fil.getName()); //返回上传文件的访问路径 getAbsolutePath()返回文件上传的绝对路径 }else { return ResultUtil.error(201, "文件上传失败,文件为空"); } }
postman请求效果图:
private String uploadPath="D:\\tomcat\\apache-tomcat-7.0.81-windows-x64\\apache-tomcat-7.0.81\\webapps\\img\\"; private String URL="http://127.0.0.1:8880/img/"; /** * 多文件上传 并返回各个文件的访问路径 * @param files * @return */ @ResponseBody @RequestMapping(value = "/upload/batch", method = RequestMethod.POST) public Msg batchUpload(@RequestParam("files")MultipartFile[] files) { String uploadedFileName = Arrays.stream(files).map(x -> x.getOriginalFilename()) .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , ")); if (StringUtils.isEmpty(uploadedFileName)) { return ResultUtil.error(201,"文件上传失败,文件为空"); } List<String> path=new ArrayList<>(); try { path= saveUploadedFiles(Arrays.asList(files)); } catch (IOException e) { return ResultUtil.error(201,"文件上传异常"+e.getMessage()); } return ResultUtil.success(path); } private List<String> saveUploadedFiles(List<MultipartFile> files) throws IOException { List<String> paths=new ArrayList<>(); for (MultipartFile file : files) { if (file.isEmpty()) { continue; } byte[] bytes = file.getBytes(); Path path = Paths.get(uploadPath + file.getOriginalFilename()); paths.add(URL + file.getOriginalFilename()); //保存上传文件的访问路径 Files.write(path, bytes); } return paths; }
请求效果图:
Java 8 中的 Stream API 详解:Stream详解
阅读全文
0 0
- SpringBoot进阶之文件上传(单文件上传/多文件上传)
- SpringBoot之文件上传
- 单文件上传、多文件上传
- 单文件上传和多文件上传
- 单/多文件上传
- 单多文件上传
- Springboot 之 多文件上传-知识林
- 单文件上传之上传图片
- springboot实现多文件上传
- SpringBoot文件上传
- springboot文件上传
- SpringBoot上传文件
- springboot 文件上传
- springboot 文件上传
- SpringBoot实现文件上传
- springboot 上传文件
- Springboot 文件上传
- SpringBoot上传文件
- scala 简介
- 关于springboot过滤器处理request参数问题
- 2017.10.16 我靠,I 服了 U
- C/C++中extern关键字详解
- programcreek
- SpringBoot进阶之文件上传(单文件上传/多文件上传)
- Node Client (2)
- 加快Android Studio 的编译
- Android屏幕适配
- Python字符串操作之字符串搜索与替换
- Android酷炫实用的开源框架(UI框架)
- linux添加开机启动项、登陆启动项、定时启动项、关机执行项等的方法
- SpringMVC的原理
- 支付--支付宝手机网站支付(WAP)