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
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
http://www.onjava.com/pub/a/onjava/2003/06/25/commons.html?page=3
try {
// Send data
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.ge tOutputStr eam());
wr.write(data); // write in a loop instead if necessary
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get InputStrea m()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
// Send data
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.ge
wr.write(data); // write in a loop instead if necessary
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
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(yo urMaxMemor ySize);
upload.setSizeMax(yourMaxR equestSize );
upload.setRepositoryPath(y ourTempDir ectory);
// Parse the request
List items = upload.parseRequest(reques t);
// 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
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(yo
upload.setSizeMax(yourMaxR
upload.setRepositoryPath(y
// Parse the request
List items = upload.parseRequest(reques
// 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
ASKER
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
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
ASKER
something like this?
import org.postgresql.jdbc3.Jdbc3 SimpleData Source;
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.c sv";
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_servi ce.activat ion_date,' YYYY-MM-DD '),'1900-0 1-01'), " +
" COALESCE(to_char(dsl_servi ce.creatio n_date,'YY YY-MM-DD') ,'1900-01- 01'), " +
" COALESCE(to_char(dsl_servi ce.telstra _appointme nt_date,'Y YYY-MM-DD' ),'1900-01 -01'), " +
"FROM " +
" dsl_service,customer " +
"WHERE " +
" dsl_service.customer_id=cu stomer.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.ge tOutputStr eam());
wr.write(data); // write in a loop instead if necessary
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get InputStrea m()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.postgresql.jdbc3.Jdbc3
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.c
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();
ds.setUser("generate_admin
ds.setPassword("test");
ds.setDatabaseName("test")
ds.setServerName("192.1.1.
Connection c = ds.getConnection();
String query =
"SELECT " +
" dsl_service.service_number
" COALESCE(to_char(dsl_servi
" COALESCE(to_char(dsl_servi
" COALESCE(to_char(dsl_servi
"FROM " +
" dsl_service,customer " +
"WHERE " +
" dsl_service.customer_id=cu
" 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.ge
wr.write(data); // write in a loop instead if necessary
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
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
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?
ASKER
i need it on the client side too.
ASKER
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.ge tOutputStr eam());
wr.write(data); // write in a loop instead if necessary
wr.flush();
Thanks
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.ge
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);
}
byte[] buf = new byte[256];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
> OutputStreamWriter wr = new OutputStreamWriter(conn.ge tOutputStr eam());
you don't need a Writer
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.ge tOutputStr eam());
should be
PrintWriter wr = new PrintWriter(new OutputStreamWriter(conn.ge tOutputStr eam()));
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html
and
>>OutputStreamWriter wr = new OutputStreamWriter(conn.ge
should be
PrintWriter wr = new PrintWriter(new OutputStreamWriter(conn.ge
>>you don't need a Writer
Yes that's true
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. getOutputS tream());
byte[] buf = new byte[256];
int n = 0;
while (-1!=(n=fin.read(buf)))
{
sout.write(buf, 0, n);
}
fin.close();
URL url = new URL("http://hostname/upload");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream sout = new BufferedOutputStream(conn.
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???
>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);
>> 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 ;-)
Well naturally because i wanted to suggest not something quite optimal deliberately - isn't that obvious ;-)
(IOW please don't make stupid comments)
ASKER
Thanks..so will this work?..i'll give it a try
import org.postgresql.jdbc3.Jdbc3 SimpleData Source;
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.c sv";
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_servi ce.activat ion_date,' YYYY-MM-DD '),'1900-0 1-01'), " +
" COALESCE(to_char(dsl_servi ce.creatio n_date,'YY YY-MM-DD') ,'1900-01- 01'), " +
" COALESCE(to_char(dsl_servi ce.telstra _appointme nt_date,'Y YYY-MM-DD' ),'1900-01 -01'), " +
"FROM " +
" dsl_service,customer " +
"WHERE " +
" dsl_service.customer_id=cu stomer.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. getOutputS tream());
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.get InputStrea m()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
import org.postgresql.jdbc3.Jdbc3
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.c
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();
ds.setUser("generate_admin
ds.setPassword("test");
ds.setDatabaseName("test")
ds.setServerName("192.1.1.
Connection c = ds.getConnection();
String query =
"SELECT " +
" dsl_service.service_number
" COALESCE(to_char(dsl_servi
" COALESCE(to_char(dsl_servi
" COALESCE(to_char(dsl_servi
"FROM " +
" dsl_service,customer " +
"WHERE " +
" dsl_service.customer_id=cu
" 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.
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.get
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
// Process line...
or you'll see no output
ASKER
will this work if the response coming back is a file rather than a string?
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get InputStrea m()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
ASKER
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) {
}
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.
it'll only handle a text file.
you should use a loop like i posted earlier to handle arbitrary response.
ASKER
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.FileNotFoundExcept ion: Upload.aspx (No such file or directory)
at java.io.FileInputStream.op en(Native Method)
at java.io.FileInputStream.<i nit>(FileI nputStream .java:106)
at java.io.FileInputStream.<i nit>(FileI nputStream .java:66)
at java.io.FileReader.<init>( FileReader .java:41)
at processVoip1.main(processV oip1.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. getOutputS tream());
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();
}
would that be because it did'nt get a response?
java.io.FileNotFoundExcept
at java.io.FileInputStream.op
at java.io.FileInputStream.<i
at java.io.FileInputStream.<i
at java.io.FileReader.<init>(
at processVoip1.main(processV
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.
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.get InputStrea m()));
that should be reading fromthe servlet response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
ASKER
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.get InputStrea m()));
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_defaultClientScri pt" 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 am i doing wrong?
thanks
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
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_defaultClientScri
<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
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?
ASKER
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.get InputStrea m()));
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.get InputStrea m()));
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();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.get
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.get
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();
}
ASKER
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
http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx
just upload any dummy file and you'll see what response you receive
ASKER
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?
ASKER
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_defaultClientScri pt" 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="FlowLay out"><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">
<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>
<!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_defaultClientScri
<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="FlowLay
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">
<INPUT name="fileProvisioningData
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
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>
ASKER
the response in the file is usaually like this
txtResponseType,txtIsSucce ssful,txtB atchID,txt ErrorCode, txtErrorDe scription
UploadResponse,TRUE,,5333,
txtResponseType,txtIsSucce
UploadResponse,TRUE,,5333,
> the response in the file is usaually like this
In what file?
In what file?
ASKER
the file Upload.aspx...
the response from the server is a file called Upload.aspx and it contains this sort of data
txtResponseType,txtIsSucce ssful,txtB atchID,txt ErrorCode, txtErrorDe scription
UploadResponse,TRUE,,5333
the response from the server is a file called Upload.aspx and it contains this sort of data
txtResponseType,txtIsSucce
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.
ASKER
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
if you go to http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx
you'll see what i mean.
Thanks
ASKER
oh...so this wont work for uploading a csv file to the server?
String fileName = "/data/usr/swiftel/SwSampl e.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. getOutputS tream());
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.get InputStrea m()));
String str;
while ((str = rd.readLine()) != null) {
System.out.println( str );
}
rd.close();
sout.close();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = "/data/usr/swiftel/SwSampl
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.
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.get
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
thats correct
ASKER
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
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
ASKER
thank you..i'll have a look
ASKER
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/SwSampl e.CSV";
MultipartPostMethod filePost =
new MultipartPostMethod(target URL);
try {
appendMessage("Uploading " + fileName + " to " + targetURL);
filePost.addParameter(file Name, targetFile);
HttpClient client = new HttpClient();
client.setConnectionTimeou t(5000);
int status = client.executeMethod(fileP ost);
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" + filePost.getResponseBodyAs String()
);
} else {
appendMessage(
"Upload failed, response=" + HttpStatus.getStatusText(s tatus)
);
}
} catch (Exception ex) {
appendMessage("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection ();
}
}
}
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/SwSampl
MultipartPostMethod filePost =
new MultipartPostMethod(target
try {
appendMessage("Uploading " + fileName + " to " + targetURL);
filePost.addParameter(file
HttpClient client = new HttpClient();
client.setConnectionTimeou
int status = client.executeMethod(fileP
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" + filePost.getResponseBodyAs
);
} else {
appendMessage(
"Upload failed, response=" + HttpStatus.getStatusText(s
);
}
} catch (Exception ex) {
appendMessage("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection
}
}
}
ASKER
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
ASKER
Thanks...does the above code look ok?
ASKER
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.NoClassDefFoundE rror: org/apache/commons/lo
gging/LogFactory
at org.apache.commons.httpcli ent.HttpMe thodBase.< clinit>(Un known Source)
at processVoip2.main(processV oip2.java: 20)
import java.util.*;
import java.io.*;
import java.net.URL;
import org.apache.commons.httpcli ent.HttpCl ient;
import org.apache.commons.httpcli ent.HttpSt atus;
import org.apache.commons.httpcli ent.method s.Multipar tPostMetho d;
String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
String fileName = "/data/usr/swiftel/SwSampl e.CSV";
MultipartPostMethod filePost =
new MultipartPostMethod(target URL);
try {
filePost.addParameter(file Name, targetFile);
HttpClient client = new HttpClient();
client.setConnectionTimeou t(5000);
int status = client.executeMethod(fileP ost);
if (status == HttpStatus.SC_OK) {
System.out.println( "ss" );
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection ();
}
i get an exception though..any idea what i'm missing? Thanks
Exception in thread "main" java.lang.NoClassDefFoundE
gging/LogFactory
at org.apache.commons.httpcli
at processVoip2.main(processV
import java.util.*;
import java.io.*;
import java.net.URL;
import org.apache.commons.httpcli
import org.apache.commons.httpcli
import org.apache.commons.httpcli
String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
String fileName = "/data/usr/swiftel/SwSampl
MultipartPostMethod filePost =
new MultipartPostMethod(target
try {
filePost.addParameter(file
HttpClient client = new HttpClient();
client.setConnectionTimeou
int status = client.executeMethod(fileP
if (status == HttpStatus.SC_OK) {
System.out.println( "ss" );
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection
}
it uses commons logging you can grab that at:
http://jakarta.apache.org/site/downloads/downloads_commons.html
http://jakarta.apache.org/site/downloads/downloads_commons.html
ASKER
thanks..i downlaoded that and had to download the commons codec package too..
ASKER
it executed fine now..but it gives me this response when i output filePost.getResponseBodyAs String()..
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(filePos t.getRespo nseBodyAsS tring());
}
<!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_defaultClientScri pt" 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">
<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>
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(filePos
}
<!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_defaultClientScri
<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
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">
<INPUT name="fileProvisioningData
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
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("fil eProvision ingData", targetFile);
filePost.addParameter("fil
ASKER
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.getResponseBodyAs String()
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.getResponseBodyAs
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.
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.
ASKER
something like this?
HostConfiguration hConf= client.getHostConfiguratio n();
hConf.setProxy("PROXYHOST ", 9999);
HostConfiguration hConf= client.getHostConfiguratio
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).
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
ASKER
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
which is this: <INPUT type="file" name="fileProvisioningData
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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/SwSampl e.CSV";
MultipartPostMethod filePost =
new MultipartPostMethod(target URL);
try {
filePost.addParameter("fil eProvision ingData", targetFile);
HttpClient client = new HttpClient();
client.setConnectionTimeou t(5000);
int status = client.executeMethod(fileP ost);
if (status == HttpStatus.SC_OK) {
System.out.println(filePos t.getRespo nseBodyAsS tring());
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection ();
}
}
is that right?
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/SwSampl
MultipartPostMethod filePost =
new MultipartPostMethod(target
try {
filePost.addParameter("fil
HttpClient client = new HttpClient();
client.setConnectionTimeou
int status = client.executeMethod(fileP
if (status == HttpStatus.SC_OK) {
System.out.println(filePos
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection
}
}
is that right?
ASKER
sorry..small change
private static File targetFile = new File("/data/usr/swiftel/Sw Sample.CSV ");
public static void main(String[] args)
{
String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
String fileName = "/data/usr/swiftel/SwSampl e.CSV";
MultipartPostMethod filePost =
new MultipartPostMethod(target URL);
try {
filePost.addParameter(targ etFile.get Name(), targetFile);
//filePost.addParameter("f ileProvisi oningData" , targetFile);
HttpClient client = new HttpClient();
client.setConnectionTimeou t(5000);
int status = client.executeMethod(fileP ost);
if (status == HttpStatus.SC_OK) {
System.out.println(filePos t.getRespo nseBodyAsS tring());
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection ();
}
}
private static File targetFile = new File("/data/usr/swiftel/Sw
public static void main(String[] args)
{
String targetURL = "http://signup.callplus.co.nz/AutoProcess/TestUpload.aspx";
String fileName = "/data/usr/swiftel/SwSampl
MultipartPostMethod filePost =
new MultipartPostMethod(target
try {
filePost.addParameter(targ
//filePost.addParameter("f
HttpClient client = new HttpClient();
client.setConnectionTimeou
int status = client.executeMethod(fileP
if (status == HttpStatus.SC_OK) {
System.out.println(filePos
} else {
System.out.println( "ss1" );
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection
}
}
ASKER
sorry it worked fine now..i was sending it to the test site which was just a wrapper..worked fine on prod..thanks..:)