Solved

Can't get anything from request.getInputStream() when trying to upload a file

Posted on 2004-10-29
794 Views
Last Modified: 2008-01-09
I'm trying to upload a file to a server using JSP. I have tried with jspsmart, io stream, jakarta commons fileupload and the one from oreilly. The 4 of them work in my testing server but none of them works in the live site. After looking for what was going on, I realized that
-> Using io Stream to store the file the following line is returning empty or null:
DataInputStream in = new DataInputStream(request.getInputStream());
So it can't read the file to store it in the server.
-> With the Jakarta Commons FileUpload, the following line does not return anything:
List fileItems = fu.parseRequest(request);
So I can't iterate it to get the files from the request.
So I guess is something about the request. But I don't have a clue why does it happens or what could I use instead of the request to get the file I want to upload.
As more information, I don't know if relevant, this is what the request.getInputStream stores:
org.apache.coyote.tomcat5.CoyoteInputStream@cd4544
The server is under Tomcat 5 and Linux.
Thanks for your help.
0
Question by:mjimeno
    29 Comments
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    That is not the right way to upload a file

    use Jakarta common's FileUploadPackage

    http://jakarta.apache.org/commons/fileupload/

    Regards
    Sudhakar
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    Oh Ok,

    you tried with FileUpload also.
    I would like to see the your code snippet

    ook at this link
    http://jakarta.apache.org/commons/fileupload/using.html

    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    Including ur html page
    0
     

    Author Comment

    by:mjimeno
    The line
    List fileItems = fu.parseRequest(request);
    belongs to the code I used with jakarta commons fileupload to upload the file. It works with my testing server but not in the live site. So, I tried several ways but nothing works. I show you this line to let you know what part of the code I'm almost sure it's not working.
    Thanks, M
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    Check if ithe request has multipart content

    boolean isMultipart = FileUpload.isMultipartContent(request);
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    As of now although this link is not necessary for ur reference this may help you.
    http://www.jguru.com/faq/view.jsp?EID=160

    But I suggest you to check for FileUpload component only,

    I think problem is because of request object only.

    chack if you are getting true value for this
     isMultipart = FileUpload.isMultipartContent(request);


    Check if you are getting any excecpions also

    Regards
    Sudhakar
    0
     

    Author Comment

    by:mjimeno
    Here is the code of JSP, the html form I guess is not necesary, just a form with a file field and multipart/form-data as the enctype.
    --------------------------------------------------------------------------------------------------------
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
         DataInputStream in = new DataInputStream(request.getInputStream(); );
         int formDataLength = request.getContentLength();            
         byte dataBytes[] = new byte[formDataLength];
         int byteRead = 0;
         int totalBytesRead = 0;
         while (totalBytesRead < formDataLength) {
              byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
              totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        String saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
                
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1,contentType.length());
        int pos;
        pos = file.indexOf("filename=\"");      
        pos = file.indexOf("\n", pos) + 1;      
        pos = file.indexOf("\n", pos) + 1;      
        pos = file.indexOf("\n", pos) + 1;      
                
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
                
        FileOutputStream fileOut = new FileOutputStream(saveFile);                  
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();
    }
    -------------------------------------------------------------------------
    Thanks, M
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    May I see your front end page that  should contain code similar to

    <FORM ENCTYPE='multipart/form-data'
     method='POST' action='/myservlet'>
    <INPUT TYPE='file' NAME='mptest'>
    <INPUT TYPE='submit' VALUE='upload'>
    </FORM>
    0
     

    Author Comment

    by:mjimeno
       <FORM name="filesForm" action="upload.jsp" method="post" enctype="multipart/form-data">
            File 1:
              <input type="file" name="file1"/>
            <br/>
            <input type="submit" name="Submit" value="Upload Files"/>
    </FORM>

    ,M
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    That model gives the problems to you when you deal with binary files dear.

    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    i mean your JSP
    0
     

    Author Comment

    by:mjimeno
    please explain me better, sudhakar
    M
    0
     
    LVL 14

    Accepted Solution

    by:
    Long back I used the code posted in following link

    which worked perfectly to me.  You may test that (though you need to do small changes )


    http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20063969.html

    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    >>DataInputStream in = new DataInputStream(request.getInputStream());

    did u try like this
    InputStream in = request.getInputStream();
    0
     
    LVL 8

    Assisted Solution

    by:kiranhk
    You can look at the struts example struts-upload.war for how to do this. Basically you have to code form like this:

    <html:form action= "uploadData.do " enctype= "multipart/form-data " >
    <html:file property= "filename " / >
    <html:submit>
    </html:form >

    You will of course need an actionForm and an action class.

    The action form would have code such as....

    Public class uploadDataForm extends ActionForm {

    protected FormFile filename;

    public FormFile getFilename() {
    return filename;
    }

    public setFilename(FormFile filename) {
    this.filename = filename;
    }
    }

    and in the action class....

    public class UploadDataAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    UploadDataForm dataForm = (UploadDataForm) form;
    FormFile file = dataForm.getFilename();

    String filename = file.getFileName();

    try {
    //retrieve the file data
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream stream = file.getInputStream();
    byte[] buffer = new byte[8192];
    int bytesRead = 0;
    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
    baos.write(buffer, 0, bytesRead);
    }
    //close the stream
    stream.close();

    // You now have the file in a ByteArrayOutputStream and you can do
    // something with it



    }
    catch (FileNotFoundException fnfe) {
    return null;
    }
    catch (IOException ioe) {
    return null;
    }
    }



    if you dont want to use JSP/Servlets and not struts way then you can check for code from here

    http://www.oop-reserch.com/cross_servlet.html
    0
     

    Author Comment

    by:mjimeno
    InputStream in = request.getInputStream(); throws the same (-1 when using in.read)
    sudhakar, your code throws me an error saying cannot resolve symobl FileOutputStream in the line FileOutputStream fout=new FileOutputStream(filehash.get("filename"));
    And kiranhk, sorry my knowledge, but can I use struts in tomcat as easy as servlets (I've no experiece with struts) and where should I place this code?
    about the oop-research, I've already tried it.
    M
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    if u r not too familiar with struts and u want to learn it you can check out here
    http://www.reumann.net/struts/main.do

    You can easily use the servlets code link which i provided for the time being.

    did u check out this for file upload
    http://www.javazoom.net/jzservlets/uploadbean/uploadbean.html

    http://www.javazoom.net/jzservlets/uploadbean/documentation/developerguide.html
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    >>sudhakar, your code throws me an error saying cannot resolve symobl FileOutputStream


    import java.io.FileOutputStream
    0
     

    Author Comment

    by:mjimeno
    kiranhk, thanks for your idea to introduce me to struts, but now I remember the live site does not have struts support (as I see taking a brief look in your tutorial, that I wiil keep to learn struts in the future) so struts is not a possibility. And about the upload bean, I preferred simple classes rather than complicated code, so I used the packages I said before. As I guess I know what is going on in the live server, I will prefer to find a solution for what I've tried (or maybe another solution as simple as the one I tried)
    Thanks, M
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    <!-- upload.jsp -->
    <%@ page import="java.io.*" %>

    <%
    String contentType = request.getContentType();
    System.out.println("Content type is :: " +contentType);
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();

    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while (totalBytesRead < formDataLength) {
    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
    totalBytesRead += byteRead;
    }

    String file = new String(dataBytes);
    String saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

    //out.print(dataBytes);

    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    //out.println(boundary);
    int pos;
    pos = file.indexOf("filename=\"");

    pos = file.indexOf("\n", pos) + 1;

    pos = file.indexOf("\n", pos) + 1;

    pos = file.indexOf("\n", pos) + 1;


    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

    FileOutputStream fileOut = new FileOutputStream(saveFile);


    //fileOut.write(dataBytes);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();

    out.println("File saved as " +saveFile);

    }
    %>
    0
     
    LVL 86

    Expert Comment

    by:CEHJ
    Your code examples certainly don't show the use of FileUpload. You should use that
    0
     

    Author Comment

    by:mjimeno
    I have used fileupload from jakarta before, but the line
    List fileItems = fu.parseRequest(request);
    does not give me a list to iterate, as if the request were empty or something like that
    M
    0
     
    LVL 86

    Expert Comment

    by:CEHJ
    Well, if that's a problem, it's certainly not going to be solved by reinventing a file upload component. You should use FileUpload and examine such a problem from that point in
    0
     

    Author Comment

    by:mjimeno
    I could use fileupload but the problem is that I don't know what should I examine. What I think is that the request does not get anything, but I don't know how to get the files from the form in another way.
    M
    0
     
    LVL 86

    Expert Comment

    by:CEHJ
    As i mentioned, start from the point of using it, since you should anyway and then take it from there
    0
     
    LVL 1

    Expert Comment

    by:Celdric
    Plain HTML has a tag for fileUpload too...
    check this:
    http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/input_file.asp
    The example is:
    <FORM NAME="oForm"
       ACTION="repost.asp"
       ENCTYPE="multipart/form-data"
       METHOD="post">
    <INPUT TYPE="file" NAME="oFile1"/>
    <INPUT TYPE="submit" VALUE="Upload File">
    </FORM>
    Just replace and ignore the Action tag, and put your own.

    Here is another HTML file upload tag reference
    http://webdesign.about.com/library/tags/bltags-inputfile.htm

    Regards!
    0
     
    LVL 1

    Expert Comment

    by:Celdric
    Oh, I think sudhakar_koundinya suggested this already, sorry for the extra post.
    Did it work?
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    did you find any of the suggestions useful?? havent heard from you for a long time
    0
     

    Author Comment

    by:mjimeno
    Sorry about the late answer. The problem was solved with the owner of the server and the owner of the software I was working within (The application I was trying to develop is going to be included in the new release of the software, so I don't need to do it myself). So, thank you all people anyway for your help, I'll split the points among the best answers.
    Thanx, M
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    Course: Foundations of Front-End Development

    Jump-start a lucrative career in front-end web development, with zero previous coding experience required. This course covers the basic programming concepts and languages required for creating engaging websites from scratch.

    Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
    Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
    Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    875 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

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now