spring mvc如何实现文件上传与下载功能

发布时间:2021-05-18 09:49:53 作者:小新
来源:亿速云 阅读:135

这篇文章给大家分享的是有关spring mvc如何实现文件上传与下载功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

文件上传

在pom.xml中引入spring mvc以及commons-fileupload的相关jar

  <!-- spring mvc -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.13.RELEASE</version>
  </dependency>
  
  <!-- 文件上传与下载 -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
  </dependency>

在springmvc.xml中加入文件上传的相关配置

 <bean id="multipartResolver" 
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
  <!-- 上传文件大小上限,单位为字节(10MB) -->
  <property name="maxUploadSize"> 
   <value>10485760</value> 
  </property> 
  <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
  <property name="defaultEncoding">
   <value>UTF-8</value>
  </property>
 </bean>

在jsp文件中加入form表单

<form action="upload" enctype="multipart/form-data" method="post">
 <table>
  <tr>
   <td>文件描述:</td>
   <td><input type="text" name="description"></td>
  </tr>
  <tr>
   <td>请选择文件:</td>
   <td><input type="file" name="file"></td>
  </tr>
  <tr>
   <td><input type="submit" value="上传"></td>
  </tr>
 </table>
</form>

添加文件上传的方法

//上传文件会自动绑定到MultipartFile中
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest request,
  @RequestParam("description") String description,
  @RequestParam("file") MultipartFile file) throws Exception {
 
 //如果文件不为空,写入上传路径
 if(!file.isEmpty()) {
  //上传文件路径
  String path = request.getServletContext().getRealPath("/file/");
  //上传文件名
  String filename = file.getOriginalFilename();
  File filepath = new File(path,filename);
  //判断路径是否存在,如果不存在就创建一个
  if (!filepath.getParentFile().exists()) {
   filepath.getParentFile().mkdirs();
  }
  //将上传文件保存到一个目标文件当中
  file.transferTo(new File(path + File.separator + filename));
  return "success";
 } else {
  return "error";
 }
 
}

感谢各位的阅读!关于“spring mvc如何实现文件上传与下载功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Spring MVC入门 —— 学SpringMVC
  2. Spring MVC 实现文件的上传和下载

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

springmvc

上一篇:SpringMVC怎么实现简单跳转方法

下一篇:ionic如何实现下拉刷新载入数据功能

相关阅读

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

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