弹出另存为窗口下载指定目录的文件

项目中要实现导出文件的功能,点导出按钮时让它弹出来一个窗口,选择存储目录和文件名

实现如下:

servlet方式

弹出来的是文件下载窗口

html代码:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Html2PdfServlet</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <form action="http://localhost:8081/createpdf/servlet/html2PdfServlet" method="get" >
	<table>
		<tr>
			<td>
				<input type="text" id="username" name="username" value="" />
			</td>
			<td>
				<input type="submit" id="submit" name="submit" value="submit" />
			</td>
		</tr>
	</table>
	</form>
  </body>
</html>


java代码:

package com.test;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;

public class Html2PdfServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		//pageContext.getServletContext().getRealPath("/")
		ServletContext sc = request.getSession().getServletContext();
		String path = sc.getRealPath(""); //值为D:\apache-tomcat-6.0.26\webapps\createpdf
		System.out.println("原path: " + path);
		//把路径中的反斜杠转成正斜杠
		path = path.replaceAll("\\\\", "/"); //值为D:/apache-tomcat-6.0.26/webapps/createpdf
		System.out.println(path);
		
		String path2 = sc.getRealPath("/");
		System.out.println("path2: " + path2);
		
		System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
		
		System.out.println("request.getRequestURI: " + request.getRequestURI());
		//获取使用的端口号
		System.out.println(request.getLocalPort());
		
		String path3 = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path3+"/";
		
		System.out.println("basepath: " + basePath);
		
		
		response.setContentType("application/pdf");
		//response.setHeader("Content-Disposition", "attachment; filename=WebReport.pdf");
		response.setHeader("Content-Disposition", "inline; filename=WebReport.pdf");
        
		StringBuffer html = new StringBuffer();
		//组装成符合W3C标准的html文件,否则不能正确解析
		html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
		.append("<head>")
		.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
		.append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
		.append("<style type=\"text/css\">img {width: 700px;}</style>")
		.append("</head>")
		.append("<body>");
		
		html.append("<center><h1>统计报表</h1></center>");
		html.append("<center>");
		html.append("<img src=\"images/chart.jpg\"/>");
		html.append("</center>");
		
		html.append("</body></html>");
        
        // parse our markup into an xml Document
        try {
        	ITextRenderer renderer = new ITextRenderer();
        	/**
        	 * 引入了新的jar包,不用再导入字体了
        	ITextFontResolver fontResolver = renderer.getFontResolver();
        	fontResolver.addFont("C:/Windows/fonts/simsun.ttc",
        			BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        	*/
            renderer.setDocumentFromString(html.toString());
            // 解决图片的相对路径问题
    		//renderer.getSharedContext().setBaseURL("file:/C:/Documents and Settings/dashan.yin/workspace/createpdf/WebRoot/images");
            //renderer.getSharedContext().setBaseURL("file:/D:/apache-tomcat-6.0.26/webapps/createpdf/images");
    		renderer.getSharedContext().setBaseURL("file:/" + path + "/images");
    		renderer.layout();
            OutputStream os = response.getOutputStream();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


Struts1方式

弹出来的是另存为窗口

html代码:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>用户登录</title>
</head>
<body>
	<h1>用户登录</h1>
	<hr>
	<form action="login.do" method="post">
		用户:<input type="text" name="username"><br>
		密码:<input type="password" name="password"><br>
		<input type="submit" value="登录">
	</form>
	
	<form action="responseAction.do" method="post">
	<table class="form_t" style="width:100%">
		<tr>
			<td>
				<input type="submit" value="测试">
				<input type="button" value="测试2" οnclick="javascript: test(this.form);" />
				<input type="button" value="导出" class="button4C"
					οnclick="javascript:test(this.form);" />
			</td>
		</tr>
	</table>
	</form>
	<script type="text/javascript">
		function test(thisform) {
			thisform.submit();
		}
	</script>
</body>
</html>


java代码:

package com.bjsxt.struts;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;


public class ResponseAction extends DispatchAction {
	
	/**
	 * 要想实现另存为下载必须满足的条件:
	 * 1.导入jar包:commons-fileupload.jar
	 * 2.发送请求必须以一个form表单的形式,且提交的时候必须是type="submit"(这一条也不对,也以可是type="button"),
	 * form的action值为相应的Action,后面不能跟方法名,跟一个form属性method="post",即:
	 * <form action="/responseAction.do" method="post">
			<table class="form_t" style="width:100%">
				<tr>
					<td>
						<input type="submit" id="submit" name="submit" value="提交"/>
					</td>
				</tr>
			</table>
		</form>
		3.相应的Action中方法名为execute,即:(这一条不对,这跟struts配置有关)
		public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	 *
	 * 现在最新总结出来:只需要满足两个条件:
	 * 导入jar包:commons-fileupload.jar
	 * 以表单提交
	 *
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		StringBuffer buffer = new StringBuffer("你好");
		
		String pdfPathName = "C:/Documents and Settings/dashan.yin/workspace/webmonitor_4/WebRoot/pdf/test.pdf";
		try {
			OutputStream out = response.getOutputStream();
			byte by[] = new byte[1024];
			File fileLoad = new File(pdfPathName);
			response.reset();
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition",
			"attachment; filename=WebReport.pdf");
			long fileLength = fileLoad.length();
			String length1 = String.valueOf(fileLength);
			response.setHeader("Content_Length", length1);
			FileInputStream in = new FileInputStream(fileLoad);
			int n;
			while ((n = in.read(by)) != -1) {
				out.write(by, 0, n);
			}
			in.close();
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值