Link to home
Start Free TrialLog in
Avatar of desiboy1974
desiboy1974

asked on

file upload

hi
  can some one give me a script or link to be able to upload a csv file to a website..i need it to load the file and retrieve the response. This site will just run on the backend retrieving data from the database, writing to a csv file and the uploading it to a url

Thanks in advance
Avatar of Mick Barry
Mick Barry
Flag of Australia image

try {

      // Send data
      URL url = new URL("http://hostname/upload");
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
      wr.write(data); // write in a loop instead if necessary
      wr.flush();

      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      // Process line...
      }
      wr.close();
      rd.close();
} catch (Exception e) {
      e.printStackTrace();
}
Avatar of desiboy1974
desiboy1974

ASKER

thanks..but this is for form based file upload requests..i'd just like a backend process that grabs data from the database, writes to a file and then uploads it to a web site
Then you need a JDBC connction to the database, execute an SQL statement to retrieve the info, e.g. a CLOB, then either write the CLOB to a POST request and send that request to a URL that can handle the file or use an FTP library (http://www.javaworld.com/javaworld/jw-04-2003/jw-0404-ftp.html) to send the file to the URL. Which do you plan to use?

If the destination URL doesn't have FTP you could use FileUpload which was why objects was suggesting that you use it for the file upload, http://jakarta.apache.org/commons/fileupload/index.html. This is pretty much the defacto standard for uploading files. Here are some previous EE threads dealing with exactly this issue, where FileUpload has been used to load files from the client-side using a form to send the files to the server..

https://www.experts-exchange.com/questions/21281045/using-a-file-in-jsp-that-was-sent-with-a-INPUT-TYPE-FILE.html
https://www.experts-exchange.com/questions/21283653/javax-servlet-http-package-in-j2se-1-4.html
https://www.experts-exchange.com/questions/21278328/How-to-UPLOAD-client-side-file-to-Server-side-DB-as-BLOB-URGENT.html

Basically you do as objects link speciifed in the form, but here are some of the options you can do in the form handler rather than just save it directly to disk in the example.

In your servlet on the final URL you merely parse the request like this:

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();

// Set upload parameters
upload.setSizeThreshold(yourMaxMemorySize);
upload.setSizeMax(yourMaxRequestSize);
upload.setRepositoryPath(yourTempDirectory);

// Parse the request
List items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
   
    //As an input stream
    InputStream uploadedStream = item.getInputStream();
   
    //or as a byte array
    //byte[] data = item.get();
}


One thing FileUPload doesn't do is validate the file to check it is a certain type of file so you will need to do that yourself
basically what i need it to do is have a jdbc connection to the database, retrive the data, wite it to a csv file and the upload it to the web site using HTTP POST and then retrive the response...
Just do a select from the db:

http://javaalmanac.com/egs/java.sql/GetRsData.html?l=rel

separate the variables and write to a file and then use the code i posted above
something like this?

import org.postgresql.jdbc3.Jdbc3SimpleDataSource;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.io.*;

public class PtSWT
{
  public static void main(String[] args)
  {
    try
    {
 String fileName = "/data/usr/swiftel/ptnew.csv";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));

      Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();

      ds.setUser("generate_admin_reports");
      ds.setPassword("test");
      ds.setDatabaseName("test");
      ds.setServerName("192.1.1.1");

      Connection c = ds.getConnection();

      String query =
        "SELECT " +
        "  dsl_service.service_number, " +
        "  COALESCE(to_char(dsl_service.activation_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "  COALESCE(to_char(dsl_service.creation_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "  COALESCE(to_char(dsl_service.telstra_appointment_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "FROM " +
        "  dsl_service,customer " +
        "WHERE " +
        " dsl_service.customer_id=customer.id " +
        "  and dsl_service.creation_date >= '2004-09-25'";

      PreparedStatement ps = c.prepareStatement(query);

      ResultSet rs = ps.executeQuery();

      while ( rs.next() )
      {
out.write(rs.getString(1));
out.write(",");
out.write(rs.getString(2));
out.write(",");
out.write(rs.getString(3));
out.write(",");
out.write(rs.getString(4));
out.write("\n");

      }

      c.close();
out.close();



    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
   
    try {
      
           // Send data
           URL url = new URL("http://hostname/upload");
           URLConnection conn = url.openConnection();
           conn.setDoOutput(true);
           OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
           wr.write(data); // write in a loop instead if necessary
           wr.flush();
      
           // Get the response
           BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
           String line;
           while ((line = rd.readLine()) != null) {
           // Process line...
           }
           wr.close();
           rd.close();
      } catch (Exception e) {
           e.printStackTrace();
}
   
  }
}

No need to create a file if you don't need it on the client side.
You can instead write the csv directly to the servlet
Yes, that's the general shape, but it needs tweaking here and there. Do you need to make a file on disk or can you just upload directly?
i need it on the client side too.
how do i make this part of the code upload the csv file?

   URL url = new URL("http://hostname/upload");
          URLConnection conn = url.openConnection();
          conn.setDoOutput(true);
          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write(data); // write in a loop instead if necessary
          wr.flush();

Thanks
That's the bit that needs tweaking most. Use a PrintWriter instead of an OutputStreamWriter and also read the file you made first with a BufferedReader, then write it with the PrintWriter
use the following loop, where in is an InputStream reading the file, and out is the output stream of the servlet connection:

byte[] buf = new byte[256];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
>  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

you don't need a Writer
Read the file like this:

http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

and

>>OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

should be

PrintWriter wr = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));

>>you don't need a Writer

Yes that's true
InputStream fin = new FileInputStream(fileName);
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream sout = new BufferedOutputStream(conn.getOutputStream());
byte[] buf = new byte[256];
int n = 0;
while (-1!=(n=fin.read(buf)))
{
   sout.write(buf, 0, n);
}
fin.close();
>>you don't need a Writer
>Yes that's true

Then why exactly have you suggested it???
Since, at the moment, you're not using the PreparedStatement, this:

>> PreparedStatement ps = c.prepareStatement(query);

can be

 Statement ps = c.createStatement(query);
>>Then why exactly have you suggested it???

Well naturally because i wanted to suggest not something quite optimal deliberately - isn't that obvious ;-)
(IOW please don't make stupid comments)
Thanks..so will this work?..i'll give it a try

import org.postgresql.jdbc3.Jdbc3SimpleDataSource;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.io.*;

public class PtSWT
{
  public static void main(String[] args)
  {
    try
    {
 String fileName = "/data/usr/swiftel/ptnew.csv";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));

      Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();

      ds.setUser("generate_admin_reports");
      ds.setPassword("test");
      ds.setDatabaseName("test");
      ds.setServerName("192.1.1.1");

      Connection c = ds.getConnection();

      String query =
        "SELECT " +
        "  dsl_service.service_number, " +
        "  COALESCE(to_char(dsl_service.activation_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "  COALESCE(to_char(dsl_service.creation_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "  COALESCE(to_char(dsl_service.telstra_appointment_date,'YYYY-MM-DD'),'1900-01-01'), " +
        "FROM " +
        "  dsl_service,customer " +
        "WHERE " +
        " dsl_service.customer_id=customer.id " +
        "  and dsl_service.creation_date >= '2004-09-25'";

Statement ps = c.createStatement(query);

      ResultSet rs = ps.executeQuery();

      while ( rs.next() )
      {
out.write(rs.getString(1));
out.write(",");
out.write(rs.getString(2));
out.write(",");
out.write(rs.getString(3));
out.write(",");
out.write(rs.getString(4));
out.write("\n");

      }

      c.close();
out.close();



    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

try {
     
          // Send data
InputStream fin = new FileInputStream(fileName);
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream sout = new BufferedOutputStream(conn.getOutputStream());
byte[] buf = new byte[256];
int n = 0;
while (-1!=(n=fin.read(buf)))
{
   sout.write(buf, 0, n);
}
fin.close();
     
          // Get the response
          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line;
          while ((line = rd.readLine()) != null) {
          // Process line...
          }
          wr.close();
          rd.close();
     } catch (Exception e) {
          e.printStackTrace();
}
   
  }
Looks ok. Of course you'll have to do something at

// Process line...

or you'll see no output
will this work if the response coming back is a file rather than a string?

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line;
          while ((line = rd.readLine()) != null) {
          // Process line...
          }
          wr.close();
          rd.close();
     } catch (Exception e) {
          e.printStackTrace();
oh sorry..this should work

try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
    } catch (IOException e) {
    }
> will this work if the response coming back is a file rather than a string?

it'll only handle a text file.
you should use a loop like i posted earlier to handle arbitrary response.
The response file will always be the same name..i've tried the code below and get this exception?

would that be because it did'nt get a response?

java.io.FileNotFoundException: Upload.aspx (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:106)
        at java.io.FileInputStream.<init>(FileInputStream.java:66)
        at java.io.FileReader.<init>(FileReader.java:41)
        at processVoip1.main(processVoip1.java:31)


    try {

           // Send data
         InputStream fin = new FileInputStream(fileName);
         URL url = new URL("http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx");
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStream sout = new BufferedOutputStream(conn.getOutputStream());
         byte[] buf = new byte[256];
         int n = 0;
         while (-1!=(n=fin.read(buf)))
         {
            sout.write(buf, 0, n);
         }
         fin.close();


           // Get the response
           BufferedReader rd = new BufferedReader(new FileReader("Upload.aspx"));
           String str;
                     while ((str = rd.readLine()) != null) {
                         System.out.println( str );
                     }
                     rd.close();
           sout.close();
      } catch (Exception e) {
           e.printStackTrace();
}
>  BufferedReader rd = new BufferedReader(new FileReader("Upload.aspx"));

that should be reading fromthe servlet response

 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
i get this output now...the output is a response file with one line of data though?

what am i doing wrong?

thanks


BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String str;
                   while ((str = rd.readLine()) != null) {
                       System.out.println( str );
                   }
                   rd.close();
          sout.close();
     } catch (Exception e) {
          e.printStackTrace();



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
        <HEAD>
                <title>TestUpload</title>
                <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1
">
                <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
                <meta name="vs_defaultClientScript" content="JavaScript">
                <meta name="vs_targetSchema" content="http://schemas.microsoft.c
om/intellisense/ie5">
        </HEAD>
        <body MS_POSITIONING="GridLayout">
                <form id="UploadForm" method="post" action="Upload.aspx" enctype
="multipart/form-data">
                        <DIV style="DISPLAY: inline; Z-INDEX: 105; LEFT: 48px; W
IDTH: 464px; POSITION: absolute; TOP: 216px; HEIGHT: 32px"
                                ms_positioning="FlowLayout"><FONT face="Arial" s
ize="5"><STRONG>Check your application
                                                status here</STRONG></FONT></DIV
>
                        <INPUT style="Z-INDEX: 101; LEFT: 48px; POSITION: absolu
te; TOP: 120px" type="submit" value="Submit File">
what is it you are expecting?  ie. what is the server meant to return?
the server returns a file called Upload.aspx..what id like to do is read the file and then do something with the data..it has just 2 lines of data..i've tried this

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String str;
                   while ((str = rd.readLine()) != null) {
                       System.out.println( str );
                   }
                   rd.close();
          sout.close();
     } catch (Exception e) {
          e.printStackTrace();
}


should it be like how you spedcifed above?

 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
           String str;
                     byte[] buf1 = new byte[256];
                         int n1 = 0;
                         while (-1!=(n1=rd.read(buf1)))
                         {

                         }

                     rd.close();
           sout.close();
      } catch (Exception e) {
           e.printStackTrace();
}

actually if you go this site, you'll see exactly what i mean

http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx

just upload any dummy file and you'll see what response you receive
it has to be a csv file though
It looks like you are already recieving the contents of the page in the response, how is it not as you were expecting?
this is what i'm receiving...i dont see a response though in that???


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
        <HEAD>
                <title>TestUpload</title>
                <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1
">
                <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
                <meta name="vs_defaultClientScript" content="JavaScript">
                <meta name="vs_targetSchema" content="http://schemas.microsoft.c
om/intellisense/ie5">
        </HEAD>
        <body MS_POSITIONING="GridLayout">
                <form id="UploadForm" method="post" action="Upload.aspx" enctype
="multipart/form-data">
                        <DIV style="DISPLAY: inline; Z-INDEX: 105; LEFT: 48px; W
IDTH: 464px; POSITION: absolute; TOP: 216px; HEIGHT: 32px"
java processVoip1\ning="FlowLayout"><FONT face="Arial" s
ize="5"><STRONG>Check your application
                                                status here</STRONG></FONT></DIV
>
                        <INPUT style="Z-INDEX: 101; LEFT: 48px; POSITION: absolu
te; TOP: 120px" type="submit" value="Submit File">
                        &nbsp;<INPUT name="fileProvisioningData" style="Z-INDEX:
 102; LEFT: 48px; POSITION: absolute; TOP: 88px"
                                type="file">
                </form>
                <form id="CheckForm" method="post" action="CheckStatus.aspx">
                        <DIV style="DISPLAY: inline; Z-INDEX: 103; LEFT: 48px; W
IDTH: 336px; POSITION: absolute; TOP: 40px; HEIGHT: 32px"
                                ms_positioning="FlowLayout"><FONT face="Arial" s
ize="5"><STRONG>Select your test file
                                                here</STRONG></FONT></DIV>
                        <INPUT id="txtBatchID" name="txtBatchID" style="Z-INDEX:
 104; LEFT: 136px; POSITION: absolute; TOP: 264px">
                        <INPUT style="Z-INDEX: 106; LEFT: 48px; POSITION: absolu
te; TOP: 296px" type="submit" value="Check Status">
                        <span id="Label1" style="Z-INDEX: 107; LEFT: 72px; POSIT
ION: absolute; TOP: 264px"><b><font face="Arial" size="2">Batch ID</font></b></s
pan>
                </form>
 </body>
</HTML>
the response in the file is usaually like this

txtResponseType,txtIsSuccessful,txtBatchID,txtErrorCode,txtErrorDescription
UploadResponse,TRUE,,5333,
> the response in the file is usaually like this

In what file?
the file Upload.aspx...

the response from the server is a file called Upload.aspx and it  contains  this sort of data

txtResponseType,txtIsSuccessful,txtBatchID,txtErrorCode,txtErrorDescription
UploadResponse,TRUE,,5333

The code CEHJ provided you with is for sending a basic request to the server, it is not suitable for uploading a file. To upload a file you need to send a multipart request.
basically when we upload the csv input file. the response from the server is a file called Upload.aspx..

if you go to http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx

you'll see what i mean.


Thanks

oh...so this wont work for uploading a csv file to the server?

String fileName = "/data/usr/swiftel/SwSample.CSV";
try {

           // Send data
         InputStream fin = new FileInputStream(fileName);
         URL url = new URL("http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx");
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStream sout = new BufferedOutputStream(conn.getOutputStream());
         byte[] buf = new byte[256];
         int n = 0;
         while (-1!=(n=fin.read(buf)))
         {
            sout.write(buf, 0, n);
         }
         fin.close();


           // Get the response
           BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
           String str;
                     while ((str = rd.readLine()) != null) {
                         System.out.println( str );
                     }
                     rd.close();
           sout.close();
      } catch (Exception e) {
           e.printStackTrace();
}
> so this wont work for uploading a csv file to the server?

thats correct
following article discusses whats required:

http://www.devx.com/Java/Article/17679/0/page/2
are there any links that will help medo the following..

1.upload a csv file to the server
2.Server sends back a response file called Upload.aspx.
3.I then read the file contents and do soemthing with it.

Thanks
httpclient should handle it for you:

http://jakarta.apache.org/commons/httpclient/
thank you..i'll have a look
something like this?

import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.io.*;
import java.net.*;


public class processVoip1
{
  public static void main(String[] args)
  {
 private File targetFile;       
 String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
 String fileName = "/data/usr/swiftel/SwSample.CSV";

MultipartPostMethod filePost =
                        new MultipartPostMethod(targetURL);

                    try {
                        appendMessage("Uploading " + fileName + " to " + targetURL);
                        filePost.addParameter(fileName, targetFile);
                        HttpClient client = new HttpClient();
                        client.setConnectionTimeout(5000);
                        int status = client.executeMethod(filePost);
                        if (status == HttpStatus.SC_OK) {
                            appendMessage(
                                "Upload complete, response=" + filePost.getResponseBodyAsString()
                            );
                        } else {
                            appendMessage(
                                "Upload failed, response=" + HttpStatus.getStatusText(status)
                            );
                        }
                    } catch (Exception ex) {
                        appendMessage("Error: " + ex.getMessage());
                        ex.printStackTrace();
                    } finally {
                        filePost.releaseConnection();
                    }

  }
}

there are no instructions how to install the commons-httpclient package on solaris..is it just a matter of untarring the package?
should just need to make the jar available to your classpath
Thanks...does the above code look ok?






i've got it to compile with the jar file etc

i get an exception though..any idea what i'm missing?  Thanks

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lo
gging/LogFactory
        at org.apache.commons.httpclient.HttpMethodBase.<clinit>(Unknown Source)
        at processVoip2.main(processVoip2.java:20)

import java.util.*;
import java.io.*;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
 String fileName = "/data/usr/swiftel/SwSample.CSV";

MultipartPostMethod filePost =
                        new MultipartPostMethod(targetURL);

                    try {
                        filePost.addParameter(fileName, targetFile);
                        HttpClient client = new HttpClient();
                        client.setConnectionTimeout(5000);
                        int status = client.executeMethod(filePost);
                        if (status == HttpStatus.SC_OK) {
                           System.out.println( "ss" );
                        } else {
                            System.out.println( "ss1" );
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        filePost.releaseConnection();
                    }
thanks..i downlaoded that and had to download the commons codec package too..
it executed fine now..but it gives me this response when i output filePost.getResponseBodyAsString()..

how do i get the data from the file..should i use filereader?

this is how i'm getting the response

if (status == HttpStatus.SC_OK) {
                           System.out.println(filePost.getResponseBodyAsString());
                        }



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
        <HEAD>
                <title>TestUpload</title>
                <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1
">
                <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
                <meta name="vs_defaultClientScript" content="JavaScript">
                <meta name="vs_targetSchema" content="http://schemas.microsoft.c
om/intellisense/ie5">
        </HEAD>
        <body MS_POSITIONING="GridLayout">
                <form id="UploadForm" method="post" action="Upload.aspx" enctype
="multipart/form-data">
                        <DIV style="DISPLAY: inline; Z-INDEX: 105; LEFT: 48px; W
IDTH: 464px; POSITION: absolute; TOP: 216px; HEIGHT: 32px"
                                ms_positioning="FlowLayout"><FONT face="Arial" s
ize="5"><STRONG>Check your application
                                                status here</STRONG></FONT></DIV
<INPUT style="Z-INDEX: 101; LEFT: 48px; POSITION: absolu
te; TOP: 120px" type="submit" value="Submit File">
                        &nbsp;<INPUT name="fileProvisioningData" style="Z-INDEX:
 102; LEFT: 48px; POSITION: absolute; TOP: 88px"
                                type="file">
                </form>
                <form id="CheckForm" method="post" action="CheckStatus.aspx">
                        <DIV style="DISPLAY: inline; Z-INDEX: 103; LEFT: 48px; W
IDTH: 336px; POSITION: absolute; TOP: 40px; HEIGHT: 32px"
                                ms_positioning="FlowLayout"><FONT face="Arial" s
ize="5"><STRONG>Select your test file
                                                here</STRONG></FONT></DIV>
                        <INPUT id="txtBatchID" name="txtBatchID" style="Z-INDEX:
 104; LEFT: 136px; POSITION: absolute; TOP: 264px">
                        <INPUT style="Z-INDEX: 106; LEFT: 48px; POSITION: absolu
te; TOP: 296px" type="submit" value="Check Status">
                        <span id="Label1" style="Z-INDEX: 107; LEFT: 72px; POSIT
ION: absolute; TOP: 264px"><b><font face="Arial" size="2">Batch ID</font></b></s
pan>
                </form>
        </body>
</HTML>
the details you are submitting are not correct, the name of the file argument looks like it should be fileProvisioningData

 filePost.addParameter("fileProvisioningData", targetFile);
i'll check the extra parameters and see if theres anything additonal to send

will this work in accepting the response file and extract the data though?

cause the response is a file called Upload.aspx with data in it

will this extract the data

filePost.getResponseBodyAsString()
Yes you're getting the response fine currently, what its sending you back is the html form for uploading the file.
A http proxy can be useful for doing this sort of thing for looking at the details of the request sent from the browser and seeing how the request from your app differs.
something like this?

HostConfiguration hConf= client.getHostConfiguration();
hConf.setProxy("PROXYHOST ", 9999);
no i mean using a proxy application to watch the traffic
Theres one available at http://www.xk72.com/charles/index.html, its nowhere near the best but should be good enough for your needs. You may not even need it though.

The page may be using cookies to control how it is accessed, so try first loading the form (as you are already doing) and then try the upload (using any cookies included with the original request).
First try with just the correct parameters, that may be enough
i've spoken to them and the only parameter that needs to be sent is the file parameter


which is this:      <INPUT type="file" name="fileProvisioningData" style="Z-INDEX:
 102; LEFT: 48px; POSITION: absolute; TOP: 88px">

the rest of the parameters in the form is for a different function..if you got to the site, thereone for file upload and the other is for a batch id process on on web page..i'm just using the file upload


i still keep getting the html form as the response..should'nt i be getting the response file upload.aspx cause if i load a file manually through the site, i get a response file back after i hit submit..any idea what i'm doing wrong?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yep ...this is what i use

private static File targetFile;
  public static void main(String[] args)
  {

 String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
 String fileName = "/data/usr/swiftel/SwSample.CSV";

MultipartPostMethod filePost =
                        new MultipartPostMethod(targetURL);

                    try {
      filePost.addParameter("fileProvisioningData", targetFile);
                        HttpClient client = new HttpClient();
                        client.setConnectionTimeout(5000);
                        int status = client.executeMethod(filePost);
                        if (status == HttpStatus.SC_OK) {
                           System.out.println(filePost.getResponseBodyAsString());
                        } else {
                            System.out.println( "ss1" );
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        filePost.releaseConnection();
                    }

  }

is that right?
sorry..small change

private static File targetFile = new File("/data/usr/swiftel/SwSample.CSV");
  public static void main(String[] args)
  {
String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
 String fileName = "/data/usr/swiftel/SwSample.CSV";

MultipartPostMethod filePost =
                        new MultipartPostMethod(targetURL);

                    try {
                                     filePost.addParameter(targetFile.getName(), targetFile);
                                      //filePost.addParameter("fileProvisioningData", targetFile);
                        HttpClient client = new HttpClient();
                        client.setConnectionTimeout(5000);
                        int status = client.executeMethod(filePost);
                        if (status == HttpStatus.SC_OK) {
                           System.out.println(filePost.getResponseBodyAsString());
                        } else {
                            System.out.println( "ss1" );
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        filePost.releaseConnection();
                    }

  }
sorry it worked fine now..i was sending it to the test site which was just a wrapper..worked fine on prod..thanks..:)