SSM网页下载文件

效果:

需要的资源:

       commons-fileupload-1.3.1.jar,commons-io-1.3.2.jar

步骤:

       1:搭建SSM框架:

       2:在配置文件springconfig.xml中添加配置

	<!-- 定义文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880" />
        <property name="maxInMemorySize" value="4096" />
    </bean>

       3:编写下载jsp文件:download.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载文件</title>
</head>
<body>
<h1>文件下载实例</h1>
	<form action="${pageContext.request.contextPath}/download.action" method="get">
		<input type="submit" value="下载">
	</form>
</body>
</html>

       4:编辑控制器:

  /**
   * 文件下载功能
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping("/download")
  @ResponseBody
  public String down(HttpServletRequest request,HttpServletResponse response) throws Exception{
      //模拟文件,myfile.txt为需要下载的文件
      String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt";
      //获取输入流
      InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
      //假如以中文名下载的话
      String filename = "下载文件.txt";
      //转码,免得文件名中文乱码
      filename = URLEncoder.encode(filename,"UTF-8");
      //设置文件下载头
      response.addHeader("Content-Disposition", "attachment;filename=" + filename);  
      //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型  
      response.setContentType("multipart/form-data"); 
      BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
      int len = 0;
      while((len = bis.read()) != -1){
          out.write(len);
          out.flush();
      }
      out.close();
      return "login2";
  }
 5:运行,成功的话页面信息如下,点击下载看是否能正常下载:

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值