首页 > 编程 > Java > 正文

springmvc模式的上传和下载实现解析

2019-11-26 08:23:39
字体:
来源:转载
供稿:网友

这篇文章主要介绍了springmvc模式下的上传和下载实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

此处上传的功能依旧是采用表格上传。文件格式依旧是

<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">

后台则是

 @RequestMapping("/upload")  public String upload(MultipartFile file,String userName,HttpServletRequest request) throws IOException {    String filename = file.getOriginalFilename();    String suffix = filename.substring(filename.lastIndexOf("."));    if(suffix.equalsIgnoreCase(".jpg")){      String uuid = UUID.randomUUID().toString();      //FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E://"+uuid+suffix));      file.transferTo(new File("D://"+System.currentTimeMillis()+suffix));//位置存储在硬盘上//      file.transferTo(new File(request.getServletContext().getRealPath("/")+"static/userImages/"+file));//      存储在项目里的目录下      request.setAttribute("result","上传成功");      return "/result.jsp";    }else{      request.setAttribute("result","上传失败");      return "/result.jsp";    }  }

相比之前的传统式上传,springmvc模式下封装了许多繁琐的过程,通过transferTo即可实现一些相应的操作

而下载也是相应的简化了许多

@RequestMapping("/download")  public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {    response.setHeader("content-disposition","attachment;filename="+filename);    ServletOutputStream outputStream = response.getOutputStream();    String path = request.getServletContext().getRealPath("images");    File file = new File(path,filename);    byte[] bytes = FileUtils.readFileToByteArray(file);    outputStream.write(bytes);    outputStream.close();  }

一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表