1

I get an assignment to figure out why PDF files can't be downloaded using Android phones. I get an URL which has access to the pdf files. Once it used HTTP protocol and there was no problems. When they change to HTTPS protocol, then the problem comes out.

I can download it with my PC using Firefox, Chrome and IE. When I try to access the file using my Android phone (Samsung Galaxy Note 2), Android 4.4.2, browser: Chrome and one whose icon is a blue globe, the blue download bar appears with the file name saying "< Untitled >" and then the download fails. I try to download other pdf file from other website and it works fine. When I use Firefox for Android, I can download it successfully and correctly. iOS and WindowsPhone have no problems I mentioned above.

Here is the code. It is written in Java Servlet along with JSP. (I only bring Java code here.) I don't wish I would get clear solutions but at least I am looking for some clues. I'm a new programmer. Please excuse me if this question sounds silly.


 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;
}

That's all I guess it's all about.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
dolkung
  • 11
  • 1
  • 3
  • 1
    can you post the URL of the pdf? and the code you are using to download the PDF? – Darpan Nov 06 '14 at 11:15
  • I'm afraid that the URL is limited to the employees and you may not be able to access it. But the link is like: ...xxx.do?mode=download&id=MS0wNjExMjAxNCAxNzU5&reportType=RLEE860&fileType=pdf I know some HTML code. I think this would be it: class="odd" onclick="popupDownload('MS0wNjExMjAxNCAxODI5','RLEE860','pdf')" Sorry I don't know any further code. – dolkung Nov 06 '14 at 11:33
  • Most likely, the Web app is doing something that Android browsers do not necessarily support that well, such as `Content-disposition`. – CommonsWare Nov 06 '14 at 12:00
  • Okay, atleast post the code that you are using to download. I have developed such application. This pdf is getting downloaded as an attachment to the url you are downloading. You just need to change headers of your request. Post the code, I may help you. – Darpan Nov 06 '14 at 12:29
  • I posted code already. I still can't download pdf files with Chrome on Android. But I managed to download those with Firefox already. Please say something. I'm desperate now. If the code is not clear, tell me. Thanks.. – dolkung Nov 12 '14 at 07:58

1 Answers1

0

You can download PDF with another way.(Downloading a PDF works the same as downloading any other binary file.)

  1. Open a HttpUrlConnection

  2. Use the connection's getInputStream() method to read the file

  3. Create a FileOutputStream and write the inputstream.

Check this post for example source code.

Community
  • 1
  • 1
samsad
  • 1,241
  • 1
  • 10
  • 15
  • Check this link also http://zacktutorials.blogspot.in/2014/07/android-downloading-and-viewing-pdf.html – samsad Nov 06 '14 at 12:25