我想在浏览器中打开/显示文件内容,但我不会工作。 这是我的代码:
@WebServlet("/Download")
public class Download extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String name = request.getParameter("id");
String sep = File.separator;
File file = new File("C:" + sep + "FILE" + sep + name);
if(!file.exists())
{
response.getWriter().print("File not found");
return;
}
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[4096];
int i = 0;
while((i = in.read(buffer)) != -1)
{
baos.write(buffer, 0, i);
}
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-Disposition", "inline; filename=help.pdf");
response.setHeader("Cache-Control", "cache, must-revalidate");
response.setHeader("Pragma", "public");
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
in.close();
baos.writeTo(bos);
baos.flush();
bos.flush();
bos.close();
}
}
我尝试用servlet类打开该文件。 我浏览器调试器,我可以看到响应正在进入,通常采用这种格式(JVBERi0xLjMNMSAwIG9iag08PC9UeXBl ...)。
感谢您的帮助
修改
在jsp站点上我用一个AJAX调用调用servlet,看起来像'id'是用户想要打开的fileName。
function downloadFile(id) {
$.ajax({
url:"Download",
type:"POST",
data:"id="+id
});
}
答案 0 :(得分:0)
我认为您应该在ajax
函数的downloadFile(id)
调用中添加此代码。
success:function(response){
$("#<Some_SPAN_OR_TextAreaID>").show();
$("#<Some_SPAN_OR_TextAreaID").html(response.responseText);
}