We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,047 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Upload File in Java

Hello Everyone,

I am looking for an example on how to upload files in Java only. What I saw recently it requires JSP also. But I only wish to use Java only. Here is an example on what I used, but it seems does not work.

Can you please provide some samples or review the code below.

Thanks in advance.

public static void FileUpload(String URLPath, String FilePath){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null;

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "*****";

          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;

          try{
              //------------------ CLIENT REQUEST
              FileInputStream fileInputStream = new FileInputStream(new File(FilePath));

              // open a URL connection to the Servlet 

              URL url = new URL(URLPath);

              // Open a HTTP connection to the URL

              conn = (HttpURLConnection) url.openConnection();

              // Allow Inputs
              conn.setDoInput(true);

              // Allow Outputs
              conn.setDoOutput(true);

              // Don't use a cached copy.
              conn.setUseCaches(false);

              // Use a post method.
              conn.setRequestMethod("POST");

              conn.setRequestProperty("Connection", "Keep-Alive");

              conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

              dos = new DataOutputStream( conn.getOutputStream() );

              dos.writeBytes(twoHyphens + boundary + lineEnd);
              dos.writeBytes("Content-Disposition: form-data; name=\"upload\";" + " filename=\"" + FilePath +"\"" + lineEnd);
              dos.writeBytes(lineEnd);

              // create a buffer of maximum size

              bytesAvailable = fileInputStream.available();
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              buffer = new byte[bufferSize];

              // read file and write it into form...

              bytesRead = fileInputStream.read(buffer, 0, bufferSize);

           while (bytesRead > 0){
               dos.write(buffer, 0, bufferSize);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);
               SimpleLog.write(FilePath + " uploaded to " + URLPath);
           }

           // send multipart form data necesssary after file data...

           dos.writeBytes(lineEnd);
           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           // close streams

           fileInputStream.close();
           dos.flush();
           dos.close();

           //System.out.println(FilePath + " uploaded to from " + URLPath);

          }catch (MalformedURLException ex){
              System.out.println("From ServletCom CLIENT REQUEST:"+ex);
          }catch (IOException ioe){
              System.out.println("From ServletCom CLIENT REQUEST:"+ioe);
          }

          //------------------ read the SERVER RESPONSE

          try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;
              while (( str = inStream.readLine()) != null){
                  //System.out.println("Server response is: " + str);
                  //System.out.println("");
              }
              inStream.close();

          }catch (IOException ioex){
              System.out.println("From (ServerResponse): " + ioex);
          }
    }

    public static void main(String args[]){
        String URLPath = "http://server:8080/ATTACHMENTS";
        String FilePath = "C:\\file.xls";
        UploadDataFile.FileUpload(URLPath, FilePath);
    }
3
Contributors
2
Replies
1 Day
Discussion Span
9 Months Ago
Last Updated
5
Views
jamojo
Light Poster
47 posts since May 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

If you are looking for uploading from a command line with FTP, you can check FTPClient class from apache (org.apache.commons.net.ftp.FTPClient) for uploading. Remember that it reads only ASCII file type. If you want a web interface, JSP is also a way to go.

Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17

What program or software is executing on the server that will read what you send it and write it to disk? You will need to tell that program the name of the file and where to save it.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0583 seconds using 2.66MB