【问题标题】:What's wrong with my code? Why can't I download pdf files with Chrome on Android?我的代码有什么问题?为什么我无法在 Android 上使用 Chrome 下载 pdf 文件?
【发布时间】:2015-01-02 20:38:47
【问题描述】:

晚上好。

我在一家公司工作。我得到了一项任务,要弄清楚为什么不能使用 Android 手机下载 PDF 文件。我得到一个可以访问 pdf 文件的 URL。一旦它使用HTTP协议,就没有问题了。当他们更改为 HTTPS 协议时,问题就出现了。

我可以在我的电脑上使用 Firefox、Chrome 和 IE 下载它。当我尝试使用我的 Android 手机(Samsung Galaxy Note 2)、Android 4.4.2、浏览器:Chrome 和图标为蓝色地球的浏览器访问文件时,会出现蓝色下载栏,文件名显示为“”然后下载失败。我尝试从其他网站下载其他 pdf 文件,它工作正常。当我使用 Firefox for Android 时,我可以成功且正确地下载它。 iOS 和 WindowsPhone 没有我上面提到的问题。

这里是代码。它是用 Java Servlet 和 JSP 编写的。 (我这里只带 Java 代码。)我不希望得到明确的解决方案,但至少我正在寻找一些线索。我是一个新程序员。如果这个问题听起来很愚蠢,请原谅。


 public ActionForward download(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

    HttpSession session = request.getSession();
    BusinessUser bu = (BusinessUser) session.getAttribute( ConfigConstant.SESSION_CURRENT_USER );
    String  id = request.getParameter(ConfigConstant.PARAMETER_ID);
    String reportId = id;
    reportId = new String(Base64.decodeBase64(reportId));
    String imgId = reportId.split(ConfigConstant.SPLITTER_DASH)[0];
    String reportType = request.getParameter("reportType"); // HardCode ๏ฟฝ๏ฟฝ๏ฟฝวค๏ฟฝ๏ฟฝ๏ฟฝ
    String fileType = request.getParameter("fileType");


    if(StringUtils.isNotEmpty(imgId)) {

        File file = fileService.getFileByfileID(imgId);

        Log log = new Log();
        log.setLogSessionID(session.getId());
        log.setLogType(ConfigConstant.LOG_TYPE_FRANCHISE_STATEMENT);
        log.setLogAction(ConfigConstant.LOG_ACTION_OPEN);
        log.setLogClass(this.getClass().getName());
        log.setLogItemId(imgId);
        log.setLogUserID(bu.getUserID());
        log.setCreateUser(bu.getFirstName() + " "   + bu.getLastName());
        log.setLogIpAddress(request.getRemoteAddr());
        logService.insertLog(log);
        log = null;

        OutputStream outputStream = null;
        CSVParse parser;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try{

            outputStream = response.getOutputStream();


            if(fileType.equalsIgnoreCase("csv")){
                bufferedReader = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(file.getContent()), "TIS-620"));

                // Microsoft Excel style
                parser = new ExcelCSVParser(bufferedReader);
                String content = "";
                String[][] allValues = parser.getAllValues();
                boolean first = true;
                boolean headTr = true;
                boolean headTd = true;
                int checkRowColor = 0;
                if(allValues != null){
                    content += "<!DOCTYPE html><html><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' pageEncoding='UTF-8' />" +
                            "<head><style type=\"text/css\">#detail{font-family: " +
                            "Arial, Helvetica, sans-serif;border-collapse:collapse;}#detail td, " +
                            "#detail th{font-size:0.7em;border:1px solid black;padding:3px 7px 2px 7px;}" +
                            "#detail th {font-size:0.9em;text-align:center;padding-top:5px;padding-bottom:4px;" +
                            "background-color:#C2CFDF;color:black;}#detail tr.alt td " +
                            "{color:#000000;background-color:#EEF2F7;}</style></head>" +
                            "<script type='text/javascript'>function submit(url){window.location = url; }</script><body>";

                    content += "<table align='center'><tr><td><button onclick='submit(\"franchiseStatement.do?mode=exportFileToCsv&id="+id+"\");'>Export to CSV</button></td></tr></table>";
                    for(int i=0;i<allValues.length;i++){
                        if(allValues[i].length ==1 && first){
                            content += "<div>"+allValues[i][0]+"</div>";
                        }else{
                            if(first){                                  
                                first = false;                                  
                                content += "<table border='1' bordercolor='black'  cellpadding='0' cellspacing='0' id='detail'>";
                            }
                            if(headTr){
                                content += "<tr bgcolor='#E2E0FF'>";
                                headTr = false;
                            }else{
                                if(checkRowColor%2 != 0){
                                    content += "<tr class='alt'>";
                                }else{
                                    content += "<tr>";
                                }                                   
                                checkRowColor++;
                                headTd = false;
                            }

                            for(int j=0;j<allValues[i].length;j++){
                                if(headTd){
                                    content += "<td align='center'><b>"+allValues[i][j]+"<b></td>";
                                }else if(org.apache.commons.lang.StringUtils.isEmpty(allValues[i][j])){
                                    content += "<td>&nbsp;</td>";
                                }else{      
                                    if(TextUtils.checkNumeric(allValues[i][j])){
                                        content += "<td align='right'>"+allValues[i][j]+"</td>";
                                    }else{
                                        content += "<td>"+allValues[i][j]+"</td>";
                                    }                                       
                                }
                            }
                            content += "</tr>";
                        }   
                    }
                    content += "</table>";
                    content += "</body></html> ";
                }

                outputStream.write(content.getBytes("UTF-8"));
            }else{

                if( file != null ){

                    response.setContentType( file.getFileContentType() );

        // if not PDF, choose open, save or cancel
                    if( ! StringUtils.equalsIgnoreCase( file.getFileContentType() , "application/pdf" ) ){

  //                            response.setHeader("Content-Disposition", "attachment; filename=\""+file.getFileName()+"\"");

                        String fileName = StringUtils.isNotEmpty( file.getFileName() ) ? file.getFileName() : "output" ;
                        try {
                            String header = "attachment; filename=\"" + fileName + "\"";
                            response.setHeader( "Content-Disposition", new String( header.getBytes( "TIS620" ) , "ISO8859-1" ) ); 
                        } catch (UnsupportedEncodingException e) {
                            LogUtils.fatal(this.getClass(),e);
                            response.setHeader("Content-disposition", "attachment; filename="+ fileName);
                        }
                    }else{
                        response.setHeader("Content-disposition", "inline;" );
                    }

                    outputStream.write( file.getContent() );

                }else{
                    // File is null.

                    response.setContentType( "application/pdf" );
                    response.setHeader("Content-disposition", "inline;" );

                    //String url = "https://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/font/" + "UPCDL.TTF" ;
                    String url = "."+ "/font/" + "UPCDL.TTF" ;

                    BaseFont baseFont = BaseFont.createFont(url, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    Font font = new Font(baseFont, 20);

                    Document document = new Document( PageSize.A4 );
                    PdfWriter.getInstance( document , outputStream );
                    document.open();

                    document.add( new Paragraph( new ThaiChunk( "๏ฟฝ๏ฟฝ่พบ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝะบ๏ฟฝ ๏ฟฝ๏ฟฝุณาติด๏ฟฝ๏ฟฝอผ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝะบ๏ฟฝ" , font ) ) );
                    document.add( Chunk.NEWLINE );
                    document.add( new Paragraph( new ThaiChunk( "Report Id : " + reportId , font ) ) );                     
                    document.close();                       
                }
            }   
        }catch(Exception ex){
            LogUtils.fatal(this.getClass(),ex);
            LogUtils.error(this.getClass(), ex);
        }finally{               
            try {                   
                if( file != null ){
                    file.setContent(null);
                }

                if( outputStream != null ){
                    outputStream.flush();
                    outputStream.close();
                }

                if( inputStream != null ){
                    inputStream.close();
                }

                if( bufferedReader != null ){
                    bufferedReader.close();                     
                }

            } catch (IOException e) {
                LogUtils.error(this.getClass(), e);
            }finally{
                file = null;
                outputStream = null;
                inputStream = null; 
                bufferedReader = null;
            }
        }           
    }
    return null;
}

我想这就是全部。如果还不够,请告诉我。提前谢谢你。

【问题讨论】:

  • 你能贴出pdf的网址吗?以及您用于下载 PDF 的代码?
  • 该网址恐怕仅限于员工,您可能无法访问。但链接是这样的: ...xxx.do?mode=download&id=MS0wNjExMjAxNCAxNzU5&reportType=RLEE860&fileType=pdf 我知道一些 HTML 代码。我想是这样的:class="odd" onclick="popupDownload('MS0wNjExMjAxNCAxODI5','RLEE860','pdf')" 抱歉,我不知道更多代码。
  • 很可能,Web 应用正在做一些 Android 浏览器不一定支持的事情,例如 Content-disposition
  • 好的,至少贴出你用来下载的代码。我开发了这样的应用程序。此 pdf 将作为您正在下载的 url 的附件下载。您只需要更改请求的标头。贴出代码,我可以帮你。
  • 我已经发布了代码。我仍然无法在 Android 上使用 Chrome 下载 pdf 文件。但我已经设法用 Firefox 下载了那些。请说点什么。我现在很绝望。如果代码不清楚,请告诉我。谢谢..

标签: android jsp servlets pdf content-disposition


【解决方案1】:

您可以通过其他方式下载 PDF。(下载 PDF 与下载任何其他二进制文件的工作方式相同。)

  1. 打开HttpUrlConnection

  2. 使用连接的getInputStream()方法读取文件

  3. 创建FileOutputStream 并写入输入流。

查看this post 示例源代码。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多