• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 381
  • Last Modified:

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
0
desiboy1974
Asked:
desiboy1974
  • 32
  • 22
  • 10
  • +1
1 Solution
 
CEHJCommented:
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();
}
0
 
desiboy1974Author Commented:
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
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
bloodredsunCommented:
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..

http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_21281045.html
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21283653.html
http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_21278328.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
0
 
desiboy1974Author Commented:
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...
0
 
CEHJCommented:
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
0
 
desiboy1974Author Commented:
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();
}
   
  }
}

0
 
objectsCommented:
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
0
 
CEHJCommented:
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?
0
 
desiboy1974Author Commented:
i need it on the client side too.
0
 
desiboy1974Author Commented:
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
0
 
CEHJCommented:
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
0
 
objectsCommented:
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);
}
0
 
objectsCommented:
>  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

you don't need a Writer
0
 
CEHJCommented:
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()));

0
 
CEHJCommented:
>>you don't need a Writer

Yes that's true
0
 
objectsCommented:
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();
0
 
objectsCommented:
>>you don't need a Writer
>Yes that's true

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

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

can be

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

Well naturally because i wanted to suggest not something quite optimal deliberately - isn't that obvious ;-)
0
 
CEHJCommented:
(IOW please don't make stupid comments)
0
 
desiboy1974Author Commented:
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();
}
   
  }
0
 
CEHJCommented:
Looks ok. Of course you'll have to do something at

// Process line...

or you'll see no output
0
 
desiboy1974Author Commented:
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();
0
 
desiboy1974Author Commented:
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) {
    }
0
 
objectsCommented:
> 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.
0
 
desiboy1974Author Commented:
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();
}
0
 
objectsCommented:
>  BufferedReader rd = new BufferedReader(new FileReader("Upload.aspx"));

that should be reading fromthe servlet response

 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
0
 
desiboy1974Author Commented:
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">
0
 
objectsCommented:
what is it you are expecting?  ie. what is the server meant to return?
0
 
desiboy1974Author Commented:
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();
}

0
 
desiboy1974Author Commented:
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
0
 
desiboy1974Author Commented:
it has to be a csv file though
0
 
objectsCommented:
It looks like you are already recieving the contents of the page in the response, how is it not as you were expecting?
0
 
desiboy1974Author Commented:
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>
0
 
desiboy1974Author Commented:
the response in the file is usaually like this

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

In what file?
0
 
desiboy1974Author Commented:
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

0
 
objectsCommented:
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.
0
 
desiboy1974Author Commented:
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

0
 
desiboy1974Author Commented:
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();
}
0
 
objectsCommented:
> so this wont work for uploading a csv file to the server?

thats correct
0
 
objectsCommented:
following article discusses whats required:

http://www.devx.com/Java/Article/17679/0/page/2
0
 
desiboy1974Author Commented:
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
0
 
objectsCommented:
httpclient should handle it for you:

http://jakarta.apache.org/commons/httpclient/
0
 
desiboy1974Author Commented:
thank you..i'll have a look
0
 
desiboy1974Author Commented:
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();
                    }

  }
}

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






0
 
desiboy1974Author Commented:
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();
                    }
0
 
objectsCommented:
it uses commons logging you can grab that at:

http://jakarta.apache.org/site/downloads/downloads_commons.html
0
 
desiboy1974Author Commented:
thanks..i downlaoded that and had to download the commons codec package too..
0
 
desiboy1974Author Commented:
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>
0
 
objectsCommented:
the details you are submitting are not correct, the name of the file argument looks like it should be fileProvisioningData

 filePost.addParameter("fileProvisioningData", targetFile);
0
 
desiboy1974Author Commented:
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()
0
 
objectsCommented:
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.
0
 
desiboy1974Author Commented:
something like this?

HostConfiguration hConf= client.getHostConfiguration();
hConf.setProxy("PROXYHOST ", 9999);
0
 
objectsCommented:
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).
0
 
objectsCommented:
First try with just the correct parameters, that may be enough
0
 
desiboy1974Author Commented:
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
0
 
objectsCommented:
did u change the name of the parameter as I mentioned above?
And make sure targetFile is an instance of File
0
 
desiboy1974Author Commented:
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?
0
 
desiboy1974Author Commented:
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();
                    }

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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 32
  • 22
  • 10
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now