文件下载.docx
《文件下载.docx》由会员分享,可在线阅读,更多相关《文件下载.docx(15页珍藏版)》请在冰豆网上搜索。
![文件下载.docx](https://file1.bdocx.com/fileroot1/2023-1/27/a2e099ee-5ca6-4c43-af62-5aae74c932ea/a2e099ee-5ca6-4c43-af62-5aae74c932ea1.gif)
文件下载
java文件下载
1.jsp实现的下载功能,图片,word,txt都可以下载
第一行代码中去掉contentType="application/x-msdownload"以后才可以下载,可以下载图片,word,tx文件都没问题。
文件下载1代码
1.<%@page language="java" pageEncoding="gb2312"
2. import=".*,java.io.*"
3.%>
4.<%
5. //关于文件下载时采用文件流输出的方式处理:
6. //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
7. response.reset();//可以加也可以不加
8. response.setContentType("application/x-download");
9. String filedownload = "D:
/primeton5/jakarta-tomcat-5.0.28/upload/2348.txt";
10. String filedisplay = "2348.txt";
11. filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
12. response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
13. OutputStream outp = null;
14. FileInputStream in = null;
15. try
16. {
17. outp = response.getOutputStream();
18. in = new FileInputStream(filedownload);
19. byte[] b = new byte[1024];
20. int i = 0;
21. while((i = in.read(b)) > 0)
22. {
23. outp.write(b, 0, i);
24. }
25. outp.flush();
26. }
27. catch(Exception e)
28. {
29. System.out.println("Error!
");
30. e.printStackTrace();
31. }
32. finally
33. {
34. if(in !
= null)
35. {
36. in.close();
37. in = null;
38. }
39. if(outp !
= null)
40. {
41. outp.close();
42. outp = null;
43. }
44. }
45.%>
2.下载txt文件可以,但是文件内容中添加了文件名和文件的下载路径。
下载jpg图片和word文件会显示乱码。
文件下载2代码
1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.<%
3.// 得到文件名字和路径
4.String filename = "2312.jpg";
5.String filepath = "D:
/primeton5/jakarta-tomcat-5.0.28/upload/";
6.// 设置响应头和下载保存的文件名
7.response.setContentType("application/octet-stream");
8.response.setHeader("content-disposition",
9."attachment; filename=\"" + filename + "\"");
10.
11.// 打开指定文件的流信息
12.java.io.FileInputStream fileinputstream =
13.new java.io.FileInputStream(filepath + filename);
14.
15.// 写出流信息
16.int i;
17.while ((i=fileinputstream.read()) !
= -1) {
18.out.write(i);
19.}
20.fileinputstream.close();
21.out.close();
22.%>
3.实际场景:
应用从文件服务器下载文件。
应用知道文件的URI.代码如下
Java代码
1.@RequestMapping(value = "/resourcelibrary/downLoadResource.do")
2.public void downLoadResource(String name,String path,HttpServletRequest request,HttpServletResponse response) {
3. //path=path.replaceAll("/", "//");
4. HttpClient httpClient = new HttpClient();
5. // 创建GET方法的实例
6. GetMethod getMethod = new GetMethod(path);
7.
8. BufferedInputStream bis = null;
9. BufferedOutputStream bos = null;
10. OutputStream fos = null;
11. InputStream fis = null;
12.
13. try {
14. response.reset();
15. response.setHeader("Content-disposition",
16. "attachment;success=true;filename ="
17. + name);
18.
19. // 使用系统提供的默认的恢复策略sysInterface
20. getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
21. //getMethod.setURI(new URI(url, charset));
22.
23. // 执行getMethod
24. int statusCode = httpClient.executeMethod(getMethod);
25.
26. fis=getMethod.getResponseBodyAsStream();
27. bis = new BufferedInputStream(fis);
28. fos = response.getOutputStream();
29. bos = new BufferedOutputStream(fos);
30. // 弹出下载对话框
31. int bytesRead = 0;
32. byte[] buffer = new byte[8192];
33. while ((bytesRead = bis.read(buffer, 0, 8192)) !
= -1) {
34. bos.write(buffer, 0, bytesRead);
35. }
36. bos.flush();
37. fis.close();
38. bis.close();
39. fos.close();
40. bos.close();
41. } catch (HttpException e) {
42. // 发生致命的异常,可能是协议不对或者返回的内容有问题
43. System.out.println("Please check your provided http address!
");
44. e.printStackTrace();
45. } catch (IOException e) {
46. // 发生网络异常
47. e.printStackTrace();
48. } finally {
49. // 释放连接
50. getMethod.releaseConnection();
51.
52. try {
53. if(fis!
=null){
54. fis.close();
55. }
56. if(bis!
=null){
57. bis.close();
58. }
59. if(fos!
=null){
60. fos.close();
61. }
62. if(bos!
=null){
63. bos.close();
64. }
65. } catch (IOException e) {
66. e.printStackTrace();
67. }
68.
69. }
70.
71. }
总结:
java.io.File读取文件,例如Filefile=newFile(path)。
path是本地服务器的路径的绝对路径,则没有问题,能读到指定文件。
如果是URI的话,会报出找不到文件。
其中会报java的斜杠转义的事情。
如果把URL转换为URI呢,例如URLurl=newURL(path);Filefile=newFile(url.toURI());这个时候会报出找不到fileprotocal的错误。
从URL读取指定文件使用File读取真的很难做到,可能有办法,但是我尝试了上面的2中方法都没有成功。
后来,想到用httpClient读取跨域的URL文件,这样写入输出流就能下载到文件,真的做到了。
httpClient的getMethod用完后,释放连接。
jsp下载服务端的文件到本地
分类:
技术集锦2013-06-0618:
13 2738人阅读 评论(3) 收藏 举报
一、list页面的js,点击list列表下面的下载按钮调用js
[javascript] viewplaincopyprint?
1.function downloadDoc(filePath,fileName){
2. var path = filePath+fileName;
3. var contextLength = "<%=request.getContextPath()%>";
4. var sp = path.substring(contextLength.length,path.length);
5. document.getElementById("path").value = sp;
6. document.getElementById("fileName").value = fileName;
7. //down_frame.location.href = path;decodeURI(path);encodeURIComponent
8. var sForm1 = document.form1;
9. sForm1.action = "<%=request.getContextPath()%>/com/icss/mdm/usermanual/servlet/StandardDocDownServlet";
10. sForm1.submit();
11.
12.}
下面是一个form表单
[html] viewplaincopyprint?
1.
通过servlet的代码如下:
[java] viewplaincopyprint?
1.package com.icss.mdm.usermanual.servlet;
2.import javax.servlet.http.HttpServletRequest;
3.import javax.servlet.http.HttpServletResponse;
4.import com.icss.mdm.base.servlet.BaseServlet;
5.import com.icss.pangu.logging.Log;
6.import com.icss.pangu.logging.LogFactory;
7.
8.public class StandardDocDownServlet extends BaseServlet {
9. private static Log log = LogFactory.getLog(StandardDocDownServlet.class);
10.
11. public void performTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
12. String path = getParameter(request, "path", true, true, false, "");
13. String fileName = getParameter(request, "fileName", true, true, false, "");
14. request.setAttribute("path", path);
15. request.setAttribute("fileName", fileName);
16. if(!
"".equals(path) && !
"".equals(fileName)){//去函数说明文档页面
17. getServletContext().getRequestDispatcher("/mdm/jsp/usermanual/DownFile.jsp").forward(request,response);
18. }
19.
20. }
21.}
下面是下载的页面:
[html] viewplaincopyprint?
1.<%@ page contentType="text/html;charset=GBK"%>
2.<%@page import=".URLEncoder"%>
3.
4.
5.
下载标准文档 6.
7.
9.
10.<%
11. //去除缓存
12. /**response.setHeader("Pragma", "No-cache");
13. response.setHeader("Cache-Control", "no-cache");
14. response.setDateHeader("Expires", 0);
15. String contextPath = request.getContextPath();**/
16.
17. //String path = request.getParameter("path");
18. //String fileName = request.getParameter("fileName");
19. String path = (String)request.getAttribute("path");//即将下载的文件的相对路径
20. String fileName = (String)request.getAttribute("fileName");//下载文件时显示的文件保存名称
21.
22. response.setContentType("application/x-download");//设置为下载application/x-download
23. String filedownload = path;//即将下载的文件的相对路径
24. String filedisplay = fileName;//下载文件时显示的文件保存名称
25. String filenamedisplay = URLEncoder.encode(filedisplay,"utf-8");
26. response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
27.
28. try
29. {
30. RequestDispatcher dis = application.getRequestDispatcher(filedownload);
31. if(dis!
= null)
32. {
33. dis.forward(request,response);
34. }
35. response.flushBuffer();
36. }
37. catch(Exception e)
38. {
39. e.printStackTrace();
40. }
41. finally
42. {
43.
44. }
45.%>
46.
47.
二、采用文件流输出的方式下载
[html] viewplaincopyprint?
1.<%@page language="java" contentType="application/x-msdownload" pageEn