更新時間:2021-09-10 10:15:35 來源:動力節(jié)點 瀏覽1886次
對請求處理方法使用void或null作為返回類型,并在方法中添加HttpServletResponse參數(shù)
將響應(yīng)的內(nèi)容類型設(shè)為文件的內(nèi)容類型
添加一個名為Content-Disposition的HTTP響應(yīng)標題,并賦值attachment; filename= fileName,這里的fileName是默認文件名,應(yīng)該出現(xiàn)在File Download(文件下載)對話框中。它通常與文件同名,但是也并非一定如此。(可選)
指定用戶、密碼登錄表單之后,設(shè)置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())) {
//設(shè)置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()) {
//設(shè)置響應(yīng)類型,這里是下載pdf文件
response.setContentType("application/pdf");
//設(shè)置Content-Disposition,設(shè)置attachment,瀏覽器會激活文件下載框;filename指定下載后默認保存的文件名
//不設(shè)置Content-Disposition的話,文件會在瀏覽器內(nèi)打卡,比如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
結(jié)果
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");
//不設(shè)置Content-Disposition的,圖像在瀏覽器內(nèi)打卡
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文件
結(jié)果
直接請求html文件,html里面的img標簽的src記錄了請求地址,發(fā)出請求,后臺控制,將圖片的內(nèi)容輸出到瀏覽器上
以上就是動力節(jié)點小編介紹的"使用SpringMVC文件下載功能",希望對大家有幫助,想了解更多可查看SpringMVC教程。動力節(jié)點在線學(xué)習(xí)教程,針對沒有任何Java基礎(chǔ)的讀者學(xué)習(xí),讓你從入門到精通,主要介紹了一些Java基礎(chǔ)的核心知識,讓同學(xué)們更好更方便的學(xué)習(xí)和了解Java編程,感興趣的同學(xué)可以關(guān)注一下。
初級 202925
初級 203221
初級 202629
初級 203743