显示文件内容

Show content of File

我想 open/show 在浏览器中查看文件内容,但我没有用。 这是我的代码:

 @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 打开该文件 class。 我使用浏览器调试器可以看到响应正在传入,通常采用这种格式(JVBERi0xLjMNMSAwIG9iag08PC9UeXBl ...)。

谢谢你帮助我

编辑

在 jsp 站点上,我使用 AJAX 调用调用 servlet,如下所示,其中 'id' 是用户要打开的文件名。

function downloadFile(id) {

$.ajax({
    url:"Download",
    type:"POST",
    data:"id="+id       
});

}

我认为您应该在 downloadFile(id) 函数中的 ajax 调用中添加此代码。

success:function(response){
            $("#<Some_SPAN_OR_TextAreaID>").show();               
            $("#<Some_SPAN_OR_TextAreaID").html(response.responseText);
        }