spring mvc配置完后实现下载功能

时间:2023-03-09 18:33:09
spring mvc配置完后实现下载功能

实现是前台:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <input id='fileName' type="text" name="fileName"/>
  12. <a href="download.do" target="blank"><button>下载</button></a>
  13. </body>
  14. <script type="text/javascript">
  15. $(function(){
  16. $('a').click(function(){
  17. var link=this.href+'?'+'fileName='+$('#fileName').val();
  18. window.open(link);
  19. return false;
  20. });
  21. });
  22. </script>
  23. </html>

前台填写要下载的文件,后台从文件夹里查找,如果没有文件则返回错误文件,否则则提供任意文件类型的下载(填写文件时必须写后缀)

  1. package hope.cs.zhku.controller;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. /******************************************************************************
  12. * 名称:UserBasicEditorController.java</br>
  13. * 日期:2011-8-15</br>
  14. * 功能:</br>
  15. * 编写:Willson Huang</br>
  16. * 复核:</br>
  17. * 其他:</br>
  18. * 历史:(说明,修改人,时间)</br>
  19. * 1.create ,Willson Huang ,2011-8-15
  20. *****************************************************************************/
  21. @Controller
  22. public class DownloadController {
  23. @RequestMapping("download.do")
  24. public void downloadFile(String fileName,HttpServletResponse response){
  25. response.setCharacterEncoding("utf-8");
  26. response.setContentType("multipart/form-data");
  27. String downName = new String((downName.getBytes(), "ISO-8859-1"); //downName是从数据库中找出的中文名,这样做是为了防止中文名乱码。
  28. response.setHeader("Content-Disposition", "attachment;fileName="+fileName);  //这里的fileName可以是保存时文件的名字,也可以换成downName自己命名的下载下来的名字。
  29. try {
  30. File file=new File(fileName);
  31. System.out.println(file.getAbsolutePath());
  32. InputStream inputStream=new FileInputStream(file);
  33. OutputStream os=response.getOutputStream();
  34. byte[] b=new byte[1024];
  35. int length;
  36. while((length=inputStream.read(b))>0){
  37. os.write(b,0,length);
  38. }
  39. inputStream.close();
  40. } catch (FileNotFoundException e) {
  41. e.printStackTrace();
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }

spring mvc配置完后实现下载功能

spring mvc配置完后实现下载功能