SpringMVC实现文件下载功能

发布时间:2020-10-14 23:43:04 作者:MrSaber
来源:脚本之家 阅读:198

本文实例为大家分享了SpringMVC文件下载的具体代码,供大家参考,具体内容如下

两个案例

  1.为登录用户提供下载服务。

  2.阻止仅通过输入网址即可获取下载。

文件下载概览

  为了将文件发送给浏览器,我们需要在控制器中完成以下操作:

案例1:为登录用户提供下载服务

Domain类

package domain;
public class Login {
 private String username;
 private String password;

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}

Controller控制器

package controller;

import domain.Login;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

@Controller
public class ResourceController {
 private static final Log logger = LogFactory.getLog(ResourceController.class);

 @RequestMapping(value = "/login")
 public String login(@ModelAttribute Login login, HttpSession session, Model model)
 {
  model.addAttribute("login",new Login());
  if("ms".equals(login.getUsername())&&"123".equals(login.getPassword()))
  {
   session.setAttribute("loggedIn",Boolean.TRUE);
   return "Main";
  }
  else
  {
   return "LoginForm";
  }
 }

 @RequestMapping(value = "/resource_download")
 public String downloadResource(HttpSession session, HttpServletRequest request, HttpServletResponse response)
 {
  if(session==null||session.getAttribute("loggedIn")==null)
  {
  return "LoginForm";
  }
  String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/data");
  File file = new File(dataDirectory,"Blog.zip");
  if(file.exists())
  {
   response.setContentType("application/octet-stream");
   response.addHeader("Content-Disposition","attachment;filename=Blog.zip");
   byte[] buffer = new byte[1024];
   FileInputStream fis =null;
   BufferedInputStream bis =null;
   try {
    fis = new FileInputStream(file);
    bis = new BufferedInputStream(fis);
    OutputStream os =response.getOutputStream();
    int i =bis.read(buffer);
    while (i!=-1) {
     os.write(buffer, 0, i);
     i=bis.read(buffer);
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }finally {
    try {
     bis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }

  }
  return null;
 }
}


编写视图

Main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>DownPage</title>
</head>
<body>
 <h5>点击链接下载文件</h5>
 <p>
  <a href="resource_download" rel="external nofollow" >Down</a>
 </p>
</body>
</html>

LoginForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>登录页面</title>
</head>
<body>
 <form:form commandName="login" action="login" method="post">
  账号: <br>
  <form:input path="username" cssErrorClass="error" id="username"/>
  <br> 密码: <br>
  <form:input path="password" cssErrorClass="error" id="password"/>
  <br> <input type="submit" value="提交">
 </form:form>
</body>
</html>

案例2:阻止仅通过输入网址即可获取下载

 @RequestMapping(value = "/resource_download")
 public String downloadResource(HttpSession session, HttpServletRequest request, HttpServletResponse response,@RequestHeader String refuer
 ){
  if(refer==null) //通过判断refer来浏览器输入网址就能下载图片的情况
  {
    return "LoginForm";
  }
  String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/data");
  File file = new File(dataDirectory,"Blog.zip");
  if(file.exists())
  {
   response.setContentType("application/octet-stream");
   response.addHeader("Content-Disposition","attachment;filename=Blog.zip");
   byte[] buffer = new byte[1024];
   FileInputStream fis =null;
   BufferedInputStream bis =null;
   try {
    fis = new FileInputStream(file);
    bis = new BufferedInputStream(fis);
    OutputStream os =response.getOutputStream();
    int i =bis.read(buffer);
    while (i!=-1) {
     os.write(buffer, 0, i);
     i=bis.read(buffer);
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }finally {
    try {
     bis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }

  }
  return null;
 }
}

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

推荐阅读:
  1. 基于SpringMVC的文件下载实例
  2. Asp.net如何实现文件下载功能

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

springmvc 文件下载 实现文件

上一篇:Express结合Webpack的全栈自动刷新

下一篇:Vue.js中兄弟组件之间互相传值实例

相关阅读

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

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