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

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.
mjimenoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sudhakar_koundinyaCommented:
That is not the right way to upload a file

use Jakarta common's FileUploadPackage

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

Regards
Sudhakar
0
sudhakar_koundinyaCommented:
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
sudhakar_koundinyaCommented:
Including ur html page
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

mjimenoAuthor Commented:
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
sudhakar_koundinyaCommented:
Check if ithe request has multipart content

boolean isMultipart = FileUpload.isMultipartContent(request);
0
sudhakar_koundinyaCommented:
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
mjimenoAuthor Commented:
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
sudhakar_koundinyaCommented:
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
mjimenoAuthor Commented:
   <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
sudhakar_koundinyaCommented:
That model gives the problems to you when you deal with binary files dear.

0
sudhakar_koundinyaCommented:
i mean your JSP
0
mjimenoAuthor Commented:
please explain me better, sudhakar
M
0
sudhakar_koundinyaCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sudhakar_koundinyaCommented:
>>DataInputStream in = new DataInputStream(request.getInputStream());

did u try like this
InputStream in = request.getInputStream();
0
kiranhkCommented:
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
mjimenoAuthor Commented:
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
kiranhkCommented:
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
sudhakar_koundinyaCommented:
>>sudhakar, your code throws me an error saying cannot resolve symobl FileOutputStream


import java.io.FileOutputStream
0
mjimenoAuthor Commented:
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
kiranhkCommented:
<!-- 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
CEHJCommented:
Your code examples certainly don't show the use of FileUpload. You should use that
0
mjimenoAuthor Commented:
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
CEHJCommented:
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
mjimenoAuthor Commented:
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
CEHJCommented:
As i mentioned, start from the point of using it, since you should anyway and then take it from there
0
CeldricCommented:
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
CeldricCommented:
Oh, I think sudhakar_koundinya suggested this already, sorry for the extra post.
Did it work?
0
kiranhkCommented:
did you find any of the suggestions useful?? havent heard from you for a long time
0
mjimenoAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.