Solved

upload a file to server

Posted on 2011-02-22
12
730 Views
Last Modified: 2012-05-11

i had a form and i am browsing a file from it and sending it to server....
I want to upload it to server... and need to parse it values...

now i can do it when i have my server and client on one machine..
so can some one tell me how to upload a file to a server and

use it in

File scpath;
saxParser.parse(scpath, handler);


I came to know that it can be done using commons file upload.jar
can some one tell me how to use...it and send that file to my saxparser...
0
Comment
Question by:shragi
  • 6
  • 3
  • 3
12 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
If you create a servlet with a form which will have
an element to browse for the file and upload it, then
you write what you uploaded to some location on your server assign any filename to it
and then feed filename of what you wrote to the SAX Parser - then
it should not  matter where is your client -  it should work for any client.

As one can understand from your question ,you already
know  how to upload the file to the server.
Then oncee you do it within a servlet - should not be any issue.

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

This is about uploading the file from the dform and reading it
in the servlet:

I do uploading the file in this way - in the form I place such element:
<input type="file" name="myFile" align="Right" size="40" id="peek" maxlength="0">

then on the next page-servlet where I read input from the form, i have such code:

public synchronized void doPost(HttpServletRequest req, HttpServletResponse res)
 throws IOException {

MultiPartRequest mpr = new MultiPartRequest(req);

  DataInputStream inputSDF = new DataInputStream(new BufferedInputStream(mpr.getInputStream("myFile")));


and  then you have stream from which you read this file.

Open in new window







0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 

Author Comment

by:shragi
Comment Utility
<html>
<head></head>
<body>
      <p>Commons File Upload Example</p>
      <form action="Commonsfileuploadservlet" enctype="multipart/form-data" method="POST">
            <input type="file" name="file1"><br>
            <input type="Submit" value="Upload File" onclick="uploadAction()"><br>
      </form>
</body>
<script language="JavaScript" type="text/javascript">
      function uploadAction() {
            document.forms[0].action = "uploadFile.do?method=uploadFile";
            document.forms[0].submit();
      }
</script>
</html>


and in action class of uploadFile I wrote below code...


DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
try {
      List  items = (List) upload.parseRequest(request);
      DataInputStream inputSDF = new DataInputStream(new BufferedInputStream(------------);//.getInputStream("myFile")));
      saxParser.parse(inputSDF, handler);
}
catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}

what should i change in the above code... and what can be place in the below line..
DataInputStream inputSDF = new DataInputStream(new BufferedInputStream(------------);
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility


I think your list may contain several items of your form,in this case it has
just one item - so you want to get the first item form your list  

after you parse it (List  items = (List) upload.parseRequest(request);), so
you say:

  FileItem item = (FileItem) items.get(0);

  and then
 DataInputStream inputSDF = new DataInputStream(new BufferedInputStream(item.getInputStream());

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (item.isFormField()) {
    } else {
        saxParser.parse(new InputSource(item.getInputStream()), handler);
    }
}
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:shragi
Comment Utility
these samples are gud for reading the file....

but what am i doing is...

when i have client and server on same machine...
i give the path to server so it uploads the file to server....

now if i have the stream i can just read the stream....

the thing is when i set the path to a document variable
 document.setFile("C://test.txt");

it creates a file in server....

so instead of stream can i get file as output...
otherwise is it possible to create file from stream... with out any temp... files...
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Of course, this is the input stream - why not to read from it and write to the output stream
and the output file?
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility
This i how I do it:

   DataInputStream inputSDF = new DataInputStream(new BufferedInputStream(item.getInputStream());

        FileOutputStream outputSDF = new FileOutputStream(filesForPMS + request + "_" + fileName.replace(' ','_'));

    
        byte [] buffer;
        int bytes_read;

         buffer = new byte[500000];
                 int countRead = 0;
      

                        while(true) {
                            bytes_read = inputSDF.read(buffer,0,buffer.length);
                            if(countRead == 0 && bytes_read == -1){
                                                        break;
                            } else if (bytes_read == -1) break;
                                                        outputSDF.write(buffer, 0, bytes_read);
                            countRead++;
                    }




              inputSDF.close();
        outputSDF.close();

Open in new window




I guess, the only thing you would not know is the file name and extension -
I assign some name myself.
If you know the type of file, it helps.

But all these things are happening on the server side - client has nothing to do
with all that - they just upload file from their computer - you receive the stream and
write new file on the server



0
 

Author Comment

by:shragi
Comment Utility
ok let me place my question clearly...

--connection established---
document.setObjectName( "file234" );
document.setContentType( "text" );
document.setFile("C://test.txt");
document.link("/Temp");               //destination folder in server
document.save();


now when i execute teh above code.... a new file with name "file234" is created...

I understood ur code in the below way....

you read inputstream byte by byte and wrote in output stream...
whats confusing for me is to what file name you wrote the output stream...
and can we directly use that filename for the below function...

document.setFile("C://test.txt");

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
to create a file all you need is


    File uploadedFile = new File("C://test.txt");
    item.write(uploadedFile);
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
And you can write to any filename you choose.
Like "C://text.txt" if you want.

I pasted a real example and I want to get files uploaded
from different clients under different names, therefore I have a special
way of constructing file name using unique request number so that
files from different users do not overwrite each other.
If you do it once, then "C://text.txt" would be fine.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

If you've heard about htaccess and it sounds like it does what you want, but you're not sure how it works... well, you're in the right place. Read on. Some Basics #1. It's a file and its filename is .htaccess (yes, with a dot in the front). #…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

728 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

9 Experts available now in Live!

Get 1:1 Help Now