?
Solved

Uploading pdf files on windows/Linux (JSP)

Posted on 2003-03-19
5
Medium Priority
?
832 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 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

Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

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.
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Suggested Courses
Course of the Month9 days, 13 hours left to enroll

762 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