Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2004-10-29
29
Medium Priority
?
862 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
Comment
Question by:mjimeno
[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
  • 11
  • 9
  • 4
  • +2
29 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12444561
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
ID: 12444593
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
ID: 12444610
Including ur html page
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:mjimeno
ID: 12444617
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
ID: 12444622
Check if ithe request has multipart content

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

Expert Comment

by:sudhakar_koundinya
ID: 12444695
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
ID: 12444712
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
ID: 12444717
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
ID: 12444740
   <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
ID: 12444742
That model gives the problems to you when you deal with binary files dear.

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12444749
i mean your JSP
0
 

Author Comment

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

Accepted Solution

by:
sudhakar_koundinya earned 225 total points
ID: 12444799
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
ID: 12444854
>>DataInputStream in = new DataInputStream(request.getInputStream());

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

Assisted Solution

by:kiranhk
kiranhk earned 225 total points
ID: 12444869
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
ID: 12445281
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
ID: 12445369
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
ID: 12445967
>>sudhakar, your code throws me an error saying cannot resolve symobl FileOutputStream


import java.io.FileOutputStream
0
 

Author Comment

by:mjimeno
ID: 12446017
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
ID: 12446127
<!-- 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
ID: 12447847
Your code examples certainly don't show the use of FileUpload. You should use that
0
 

Author Comment

by:mjimeno
ID: 12447873
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
ID: 12447926
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
ID: 12448137
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
ID: 12448245
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
ID: 12456952
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
ID: 12456974
Oh, I think sudhakar_koundinya suggested this already, sorry for the extra post.
Did it work?
0
 
LVL 8

Expert Comment

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

Author Comment

by:mjimeno
ID: 12574618
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

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

610 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