程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> SpringMVC實現文件下載功能

SpringMVC實現文件下載功能

編輯:關於JAVA

SpringMVC實現文件下載功能。本站提示廣大學習愛好者:(SpringMVC實現文件下載功能)文章只能為提供參考,不一定能成為您想要的結果。以下是SpringMVC實現文件下載功能正文


本文實例為大家分享了SpringMVC文件下載的具體代碼,供大家參考,具體內容如下

兩個案例

  1.為登錄用戶提供下載服務。

  2.阻止僅通過輸入網址即可獲取下載。

文件下載概覽

  為了將文件發送給浏覽器,我們需要在控制器中完成以下操作:

對請求處理方法使用void返回類型,並且在方法中添加HttpServletResponse參數。 將響應的內容類型設為文件的內容類型。Content-Type標題在某個實體的body中定義數據的類型,並包含媒體類型和子類型標識符。如果不清楚內容類型,並且希望浏覽器失始終顯示保存對話框,則將它設為APPLICATION/OCTET-STREAM。這個值時不區分大小寫的。 添加一個名為Content-Disposition的HTTP響應標題,並賦值attachment;filename=fileName,這裡的fileName是默認的文件名。

案例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>
 <h4>點擊鏈接下載文件</h4>
 <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;
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

[db:作者簡介][db:原文翻譯及解析]
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved