使用springMVC实现上传下载图片

深藏阁楼爱情的钟 2023-03-14 05:48 106阅读 0赞

上传多张图片代码:

  1. public static final String PICTUREURL = "/mnt/pic/";//图片路径
  2. public static final String PC_PICTUREURL = "E:\\pic";//图片路径
  3. @RequestMapping("/uploadPics.do")
  4. public RetObj uploadPics(@Param("file") MultipartFile[] files,@Param("trendId") Integer trendId){
  5. RetObj ret = new RetObj();
  6. try {
  7. if (files!=null &&files.length>0){
  8. List<Picture> result = new LinkedList<>();
  9. int i =1;
  10. for (MultipartFile file : files){
  11. String filename = "picture_" + UUID.randomUUID() + ".jpg";//生成唯一图片路径
  12. if (!file.isEmpty()) {
  13. try {
  14. File filepath = new File(PC_PICTUREURL);
  15. if (!filepath.exists())
  16. filepath.mkdirs();
  17. // 文件保存路径
  18. String savePath = PC_PICTUREURL + filename;
  19. // 转存文件
  20. file.transferTo(new File(savePath));
  21. //图片路径存到数据库
  22. Picture picture = new Picture();
  23. picture.setTrendid(trendId);
  24. picture.setPath(savePath);
  25. picture.setSort(i);
  26. pictureService.insert(picture);
  27. i++;
  28. result.add(picture);
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. ret.setObj(result);
  35. }else {
  36. ret.Fail("请选择上传的图片");
  37. return ret;
  38. }
  39. }catch (Exception e){
  40. log.error("图片上传失败"+ ExceptionUtil.getStackStr(e));
  41. ret.Fail("网络异常");
  42. }
  43. return ret;
  44. }

查看图片代码:

  1. @RequestMapping("/getPic.do")
  2. public void getPic(HttpServletResponse response, @Param("url") String url){
  3. File file = new File(url);
  4. FileInputStream fis =null;
  5. try {
  6. if (!file.exists()){
  7. return;
  8. }
  9. fis = new FileInputStream(file);
  10. final byte[] buf = new byte[1024];
  11. while (fis.read(buf)>0){
  12. response.getOutputStream().write(buf);
  13. }
  14. }catch (Exception e){
  15. log.error("图片上传失败"+ ExceptionUtil.getStackStr(e));
  16. }finally {
  17. if (fis!=null){
  18. try {
  19. fis.close();
  20. }catch (Exception e){
  21. }
  22. }
  23. response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springmvc实现图片

    springmvc实现多图片上传: 主要是项目要做的是一个发表分享的功能,就有点像微信发朋友圈那样,一个内容文字和图片显示。 思路:用form表单提交,在f