我有一个建议去解决你的问题。
我通常创建一个servlet,负责下载各种格式的文件:XLS、PDF…
下面是一个如何做到这一点的示例:
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
String contentType = null;
if (fileName.endsWith("xls")) {
contentType = "application/octet-stream";
} else if (fileName.endsWith("pdf")) {
contentType = "application/pdf";
} else {
throw new RuntimeException("File type not found");
}
byte[] file = getFileOnServer(fileName);
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.setHeader("charset", "iso-8859-1");
response.setContentType(contentType);
response.setContentLength(file.length);
response.setStatus(HttpServletResponse.SC_OK);
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(file, 0, file.length);
outputStream.flush();
outputStream.close();
response.flushBuffer();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
private byte[] getFileOnServer(String fileName) {
//implement your method to get the file in byte[]
return null;
}
}
因此,您可以通过URL调用servlet:
http://localhost:8080/downloadServlet?fileName=myExcel.xls
或形式:
<form id="myDownloadServlet" action="downloadServlet" method="post">
<input type="text" id="fileName" name="fileName" />
<input type="submit" id="btnDownload" name="btnDownload" value="Download File" />
</form>
不要忘记配置web.xml或使用注释@webservlet。
我希望我能帮上忙。