更新時間:2021-09-10 10:15:35 來源:動力節點 瀏覽1876次
對請求處理方法使用void或null作為返回類型,并在方法中添加HttpServletResponse參數
將響應的內容類型設為文件的內容類型
添加一個名為Content-Disposition的HTTP響應標題,并賦值attachment; filename= fileName,這里的fileName是默認文件名,應該出現在File Download(文件下載)對話框中。它通常與文件同名,但是也并非一定如此。(可選)
指定用戶、密碼登錄表單之后,設置session,然后才可以下載文件:/WEB-INF/data/secret.pdf
Controller代碼
@Controller
public class ResourceController {
private static final Log logger = LogFactory.getLog(ResourceController.class);
/**
* @param login @ModelAttribute 注解接受表單中的login對象
* @param session
* @param model
* @return
*/
@RequestMapping(value="/login")
public String login(@ModelAttribute Login login, HttpSession session, Model model) {
System.out.println(login);
//與jsp中的標簽綁定
model.addAttribute("login", new Login());
if ("paul".equals(login.getUserName()) &&
"secret".equals(login.getPassword())) {
//設置session
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");
System.out.println(dataDirectory);
File file = new File(dataDirectory, "secret.pdf");
if (file.exists()) {
//設置響應類型,這里是下載pdf文件
response.setContentType("application/pdf");
//設置Content-Disposition,設置attachment,瀏覽器會激活文件下載框;filename指定下載后默認保存的文件名
//不設置Content-Disposition的話,文件會在瀏覽器內打卡,比如txt、img文件
response.addHeader("Content-Disposition",
"attachment; filename=secret.pdf");
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
// if using Java 7, use try-with-resources
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 (IOException ex) {
// do something,
// probably forward to an Error page
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
}
return null;
}
}
LoginForm.jsp
Main.jsp
結果
Controller代碼
@Controller
public class ImageController {
private static final Log logger = LogFactory.getLog(ImageController.class);
@RequestMapping(value="/image_get/{id}", method = RequestMethod.GET)
public void getImage(@PathVariable String id,
HttpServletRequest request,
HttpServletResponse response,
@RequestHeader String referer) {
//referer記錄了該請求是從哪個鏈接過來的,可以用來判斷請求是否合法
if (referer != null) {
System.out.println(referer);
String imageDirectory = request.getServletContext().
getRealPath("/WEB-INF/image");
File file = new File(imageDirectory,
id + ".jpg");
if (file.exists()) {
response.setContentType("image/jpg");
//不設置Content-Disposition的,圖像在瀏覽器內打卡
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
// if you're using Java 7, use try-with-resources
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 (IOException ex) {
// do something here
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
}
}
}
}
html文件
結果
直接請求html文件,html里面的img標簽的src記錄了請求地址,發出請求,后臺控制,將圖片的內容輸出到瀏覽器上
以上就是動力節點小編介紹的"使用SpringMVC文件下載功能",希望對大家有幫助,想了解更多可查看SpringMVC教程。動力節點在線學習教程,針對沒有任何Java基礎的讀者學習,讓你從入門到精通,主要介紹了一些Java基礎的核心知識,讓同學們更好更方便的學習和了解Java編程,感興趣的同學可以關注一下。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習