我有一个问题,我不确切知道如何解决,我希望这会解释它你需要理解的好:
我有一个在Internet Explorer 11上预览的流式pdf文件,当我点击“另存为”时,要下载的文件的默认名称是此pdf流式传输的页面名称,我关注的是我的方式可以找到一种在响应时设置此页面名称的方法,这样这个pdf插件就会抓住并将其放在对话框中
答案 0 :(得分:0)
在你的HttpResponse中,你需要像这样设置Content-Disposition
标题:
Content-Disposition: inline; filename="myfile.txt"
除了让默认的PDF查看器识别出文件类型外,您还需要将Content-Type
响应标头设置为:application / pdf like:
Content-Type: application/pdf
这是一个正确执行此操作的示例servlet:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String pdfFileName = "pdftest.pdf";
String contextPath = getServletContext().getRealPath(File.separator);
File pdfFile = new File(contextPath + pdfFileName);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
}