最近,我为Excel添加了一些 导出按钮(ApachePOI)和pdf(wkhtmltopdf)。
我想要的是什么:
**我应该更多地使用MIME类型吗?*
String fileExtension ="application/x-www-form-urlencoded";
if (extension.equals("pdf"))
{
sURLforRequest = GWT.getHostPageBaseURL() + "requiredPDF";
fileExtension = "application/pdf";
}
else if (extension.equals("xls"))
{
sURLforRequest = GWT.getHostPageBaseURL() + "requiredXLS";
fileExtension = "application/x-www-form-urlencoded";
}
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, sURLforRequest);
//this is important
builder.setHeader("Content-type", fileExtension);
//builder.setHeader("Content-type", "application/x-www-form-urlencoded");
//builder.setHeader("Content-type", "application/octet-stream");
builder.sendRequest(sData, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
//TODO: replace with servleet link
Window.open(sURLforRequest, "_parent", "location=no");
}
@Override
public void onError(Request request, Throwable exception) {
MessageBox.alert("Request error","The page doesn't open", null);
}
});
正如您所见,我在POST请求中发送了一些数据,并调用GET方法以空白显示服务器生成的文件(如果您更好地了解如何组织此操作,请分享)。
**暂时没什么特别的*
@Override
public void doPost(HttpServletRequest request, HttpServletResponse resp)
throws javax.servlet.ServletException, java.io.IOException
{
try {
request.setCharacterEncoding("utf-8");
session = request.getSession();
//global
session.setAttribute("vDateFrom",request.getParameter("vDateFrom"));
...
session.setAttribute("vChartType",request.getParameter("vChartType"));
//doPost(request,resp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
**因为我从客户端使用window.open()方法再次调用servlet,感觉没有任何事情发生(这当然太糟糕了)*
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
//CreateHtmlFile();
request.setCharacterEncoding("utf-8");
lDateFrom = Long.parseLong(request.getSession().getAttribute("vDateFrom").toString());
...
CreateHtmlFile(...);
ConvertHTMLtoPDF(servletContext.getRealPath("wkhtmltopdf/wkhtmltopdf.exe"),
servletContext.getRealPath("PDFtemplate/requiredPDF.html"),
servletContext.getRealPath("PDFtemplate/Report.pdf"));
//Now I have required .pdf-files,
//BUT HOW TO SEND IT TO CLIENT SIDE WITH BROWSER ASK WHAT TODO
//I used to call this before, but it seems not so correct
//response.sendRedirect(servletContext.getRealPath("PDFtemplate/Report.pdf"));
//What is I'm thinking about
BufferedReader reader = new BufferedReader(
new FileReader(servletContext.getRealPath("XLStemplate/reportXLS.xlsx")));
response.setContentType("application/pdf; charset=UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
char[] buf = new char[4 * 1024]; // 4Kchar buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
out.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
我为pdf带了一个servlet,在我遇到问题或不确定的地方写了一些评论。
所以我的麻烦是:
使用客户端的一个请求
在没有任何行为无效的情况下提高效率
将文件发送到客户端,浏览器显示todo对话框(打开 或保存,确定或取消)?