?
Solved

Uploading pdf files on windows/Linux (JSP)

Posted on 2003-03-19
5
Medium Priority
?
833 Views
Last Modified: 2008-02-01
Hi All

I am having problems uploading pdf files on the server. I have attached a file that works fine. it allows me to upload .swf, .jpg, .gif, .mov, .mp3, .txt, .zip and various other but not .pdf. And the amazing thing is that it happens on windows platform (Server Platform). The same code works fine on linux. I can open uploaded .pdf files without any error (uploaded using tomcat-linux). However I get error while opening uploaded .pdf files (uploaded using JRUN OR Tomcat -- Windows).

Can some one please tell me what is going on? I do not understand what is wrong with this code. Can someone please help me understand what is wrong and how to fix this?


On line 4 change the value to the path where you wish to upload pdf files:

String savePath="/etc/jakarta-tomcat-4.1.12/webapps/";

1. Rename the attachment to .jsp
2. For the time being I have hard coded the file name to test23.pdf so please delete this file before you use this upload file code second time.


Just run the attachment (After renaming and using http://local.....) to test experience yourself. It will display 2 fields:

1. Type in anything in the first field and then point to a pdf file using the browse... button.


Code for JSP can either be downloaded from:
http://webforums.macromedia.com/attachments/testFileUpload.txt

or see below:

##############################################################################
######################     Code  #############################################
##############################################################################

<pre>
<%@ page import="javax.servlet.http.HttpServletRequest, javax.servlet.ServletInputStream, java.util.Dictionary, java.util.Hashtable, java.io.PrintWriter, java.io.BufferedWriter, java.io.FileWriter, java.io.IOException, java.io.*, java.util.*, java.util.Date, java.text.SimpleDateFormat" %>
<%
      if (request.getParameter("submit") != null){
              String savePath="/etc/jakarta-tomcat-4.1.12/webapps/";
              String filepath="";
              String filename="test23.pdf";
              String contentType="";
              Dictionary fields;
              Vector requVarValue = new Vector();
              Vector requVarName = new Vector();
      
      
          ServletInputStream in = request.getInputStream();
            
          
            out.println("<br><BR><BR><BR><BR><BR><BR>yyyyyyyyyyyyyyy<br><Br><Br><Br><br><br>");
            byte[] line = new byte[128];
          int i = in.readLine(line, 0, 128);
          if (i < 3)
            return;
          int boundaryLength = i - 2;
      
          String boundary = new String(line, 0, boundaryLength);
            //-2 discards the newline character
          fields = new Hashtable();
            
          while (i != -1) {
            String newLine = new String(line, 0, i);
             
            if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
      
                  if (newLine.indexOf("filename=\"") != -1) {
                
                    if ( !(filename==null) && !(filename.equals("")) )
                {
                          //this is the file content
                      i = in.readLine(line, 0, 128);
                     
                          int pos = newLine.indexOf("name=\"");
                          int endPos = newLine.indexOf(";",pos+6);
                          String fieldName = newLine.substring(pos+6, endPos-1);
                         
                      i = in.readLine(line, 0, 128);
                      // blank line
                      i = in.readLine(line, 0, 128);
                      newLine = new String(line, 0, i);
                        out.println("<BR><BR>Save Path:"+savePath+"<BR><BR>");  
                      PrintWriter pw = new PrintWriter(new BufferedWriter(new
                        FileWriter((savePath==null? "/etc/jakarta-tomcat-4.1.12/webapps/" : savePath) + filename)));
                      while (i != -1 && !newLine.startsWith(boundary)) {
                        // the problem is the last line of the file content
                        // contains the new line character.
                        // So, we need to check if the current line is
                        // the last line.
                        i = in.readLine(line, 0, 128);
                              
                              
                        if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
                          && (new String(line, 0, i).startsWith(boundary)))
                          pw.print(newLine.substring(0, newLine.length()-2));
                        else
                          pw.print(newLine);
                                
                              out.println("<BR>Text: "+newLine);
                        newLine = new String(line, 0, i);
            
                      }
                      pw.close();
                          out.println("<BR><BR><BR>End File:");
                    }
              }
              
            }
            i = in.readLine(line, 0, 128);
      
          } // end while
      }
%>
<html>
<head><title></title></head>

<body>
      <form action="?submit=yes" method="post"  enctype="multipart/form-data">
            <input type="text" name="testName" size=30>
            <input type=file name=textFile size=40>
            <input type=submit name=submit value=submit>
      </form>
</body>
</html>

</pre>



##############################################################################






Thanks
Viv
0
Comment
Question by:_viv
2 Comments
 

Accepted Solution

by:
ceturc earned 140 total points
ID: 8277454
Hello Viv:

This code makes an assumption that only one HTTP header will be provided by the browser.  In the case of HTTP Upload of PDF in Windows, the browser inserts an extra, invalid header into the mix - which causes the code to get out-of-sync with the data stream.  If you look at your corrupted uploaded PDF files - they contain an extra two bytes right at the beginning - a CR/LF pair.

This is quickly fixed by fortifying the code to wait for the entire browser file header to complete before writing to the file.  This is a one-line change in the code you provided.

-Chuck

Here's a code fragment around line 40 that contains the one-line fix:
-------------------------------------------
int pos = newLine.indexOf("name=\"");
int endPos = newLine.indexOf(";",pos+6);
String fieldName = newLine.substring(pos+6, endPos-1);

// Below WAS: i = in.readLine(line, 0, 128);
// Skip over browser-provided headers
while( (i = in.readLine(line, 0, 128))  > 2) { }
// read first line of file
i = in.readLine(line, 0, 128);
newLine = new String(line, 0, i);
-------------------------------------------

Here's the entire JSP with the fix included:

-------------------------------------------
<pre>
<%@ page import="javax.servlet.http.HttpServletRequest, javax.servlet.ServletInputStream, java.util.Dictionary, java.util.Hashtable, java.io.PrintWriter, java.io.BufferedWriter, java.io.FileWriter, java.io.IOException, java.io.*, java.util.*, java.util.Date, java.text.SimpleDateFormat" %>
<%
     if (request.getParameter("submit") != null){
            String savePath="/etc/jakarta-tomcat-4.1.12/webapps/";
            String filepath="";
            String filename="test23.pdf";
            String contentType="";
            Dictionary fields;
            Vector requVarValue = new Vector();
            Vector requVarName = new Vector();
     
     
         ServletInputStream in = request.getInputStream();
         
         
          out.println("<br><BR><BR><BR><BR><BR><BR>yyyyyyyyyyyyyyy<br><Br><Br><Br><br><br>");
          byte[] line = new byte[128];
         int i = in.readLine(line, 0, 128);
         if (i < 3)
           return;
         int boundaryLength = i - 2;
     
         String boundary = new String(line, 0, boundaryLength);
          //-2 discards the newline character
         fields = new Hashtable();
         
         while (i != -1) {
           String newLine = new String(line, 0, i);
           
           if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
     
               if (newLine.indexOf("filename=\"") != -1) {
               
                 if ( !(filename==null) && !(filename.equals("")) )
               {
                      //this is the file content
                    i = in.readLine(line, 0, 128);
                   
                      int pos = newLine.indexOf("name=\"");
                      int endPos = newLine.indexOf(";",pos+6);
                      String fieldName = newLine.substring(pos+6, endPos-1);
                    // Below WAS: i = in.readLine(line, 0, 128);
                    // Skip over browser-provided headers
                    while( (i = in.readLine(line, 0, 128))  > 2) { }
                    // read first line of file
                    i = in.readLine(line, 0, 128);
                    newLine = new String(line, 0, i);
                    out.println("<BR><BR>Save Path:"+savePath+"<BR><BR>");  
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new
                      FileWriter((savePath==null? "/etc/jakarta-tomcat-4.1.12/webapps/" : savePath) + filename)));
                    while (i != -1 && !newLine.startsWith(boundary)) {
                      // the problem is the last line of the file content
                      // contains the new line character.
                      // So, we need to check if the current line is
                      // the last line.
                      i = in.readLine(line, 0, 128);
                         
                         
                      if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
                        && (new String(line, 0, i).startsWith(boundary)))
                        pw.print(newLine.substring(0, newLine.length()-2));
                      else
                        pw.print(newLine);
                           
                         out.println("<BR>Text: "+newLine);
                      newLine = new String(line, 0, i);
         
                    }
                    pw.close();
                      out.println("<BR><BR><BR>End File:");
                 }
             }
             
           }
           i = in.readLine(line, 0, 128);
     
         } // end while
     }
%>
<html>
<head><title></title></head>

<body>
     <form action="?submit=yes" method="post"  enctype="multipart/form-data">
          <input type="text" name="testName" size=30>
          <input type=file name=textFile size=40>
          <input type=submit name=submit value=submit>
     </form>
</body>
</html>

</pre>
0
 

Author Comment

by:_viv
ID: 8289527
Hi Chuck,

Thanks a lot! I made appropriate changes and it works however not for every file. Please try to upload DocBox.pdf file.

If you have acrobat 5.0 installed then it should be in Acrobat root\Help\ENU\DocBox.pdf folder. If you don't have acrobat installed then I can email that to you. There are some other PDF files that don't work either.

Not very sure why is this working on some pdf files and not for others.


Cheers...
Viv
0

Featured Post

Managing Security & Risk at the Speed of Business

Gartner Research VP, Neil McDonald & AlgoSec CTO, Prof. Avishai Wool, discuss the business-driven approach to automated security policy management, its benefits and how to align security policy management with business processes to address today's security challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Meet the world's only “Transparent Cloud™” from Superb Internet Corporation. Now, you can experience firsthand a cloud platform that consistently outperforms Amazon Web Services (AWS), IBM’s Softlayer, and Microsoft’s Azure when it comes to CPU and …
ADCs have gained traction within the last decade, largely due to increased demand for legacy load balancing appliances to handle more advanced application delivery requirements and improve application performance.
In this video I will demonstrate how to set up Nine, which I now consider the best alternative email app to Touchdown.
The video will let you know the exact process to import OST/PST files to the cloud based Office 365 mailboxes. Using Kernel Import PST to Office 365 tool, one can quickly import numerous OST/PST files to Office 365. Besides this, the tool also comes…

593 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question