Upload file into XAMPP Server using HttpURLConnection - java

I am trying to upload file into XAMPP server but I could not see any file into server project folder.But I see byte writing completed.What is the problem in my code.Please help me anybody.
Sample code::
import java.io.*;
import java.net.*;
public class ServletCom {
public static void main(String[] args)
throws Exception
{
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "C:\\Users\\hossain\\Desktop\\photo\\image\\text.txt";
String fileName="text.txt";
String lineEnd = "";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://local.ebajar/";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileName + "\"" + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name="upload";"+ " filename="" + exsistingFileName +""" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
System.out.println("write complete........" );
// close streams
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
System.out.println("From ServletCom CLIENT REQUEST:"+ex);
}
catch (IOException ioe)
{
System.out.println("From ServletCom CLIENT REQUEST:"+ioe);
}
catch (Exception e)
{
System.out.println("From ServletCom CLIENT REQUEST:"+e);
}
}
}

Related

Send parameters while uploading file to PHP source

I'm using this class to upload image to php server from my android app.
But I want to send some parameters such as custom file name, user who uploaded the file etc.
Is there any way to send some parameters while uploading the file?
Example: name=newimage&uploadedby=username
private class UploadFileAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String sourceFileUri = "/mnt/sdcard/abc.png";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (sourceFile.isFile()) {
try {
String upLoadServerUri = "http://website.com/abc.php?";
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE",
"multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math
.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,
bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn
.getResponseMessage();
if (serverResponseCode == 200) {
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "Executed";
}
}
Is there any way to do this with header request, like this:
conn.setRequestProperty("parameters","name=filename&uploadedby=username");
yes it is possible
I am not a java developer but in PHP you can receive such data in 2 ways: as parameter in the URL which will be available in PHP in the $_GET array
Example, change your URL to:
String upLoadServerUri = "http://website.com/abc.php?filename=blabla&anotherparam=1234";
then in PHP: echo $_GET['filename']. $_GET is also available if you are POSTing your request.
or/and you can do this in your POST. Your POST request can contain as many extra params as you need. Here is an example how you could do this.

Unable to Send parameter In HttpURLConnection

i need to send a data to server using multipart i have successfully sending image to server using HttpURLConnection Multipart image is loading successfully but i am sending id also but id is not sending to server. so can you help me where is error .i
public String uploadData() {
String fileName = mRealProfilePicPath;
// Log.e("mrealpath",fileName);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(mRealProfilePicPath);
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// URL url = new URL("http://stank.cwsdev3.biz/text.php/");
// URL url = new
// URL(AppUtills.BASE_URL+"user/update_profile?&dump=1");
URL url = new URL(AppUtills.BASE_URL + "user/update_profile?");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("profilepic", fileName);
conn.setRequestProperty("first_name", firstName);
// conn.setRequestProperty("dump","1");
// conn.setRequestProperty("id",
// AppPreference.getUserId(con,AppUtills.USERID));
dos = new DataOutputStream(conn.getOutputStream());
String param1 = AppPreference.getUserId(con, AppUtills.USERID);
dos.writeBytes("Content-Disposition: form-data; name=\"id\""
+ lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + param1.length() + lineEnd); // unable to upload this
dos.writeBytes(lineEnd);
dos.writeBytes(param1 + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"profilepic\";filename=\""
+ fileName + "\"" + lineEnd); // image uploading
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.e("uploadFile", "HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
int responseCode = conn.getResponseCode();
Log.e("TAG, POST Response Code :: ", "" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.i("TAG", response.toString());
return response.toString();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
return "no";
}

Upload a file using Java program to server- server response gives Content-Length=0

I am trying to upload a file to a server. I have write the client code in java. Server code is written in php.
I am getting Content-Length=0 in server response. But when I upload a file using chrome rest client it gives the content length. Here is my java client code:
private String FileUploading(String url1) throws Exception
{
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
FileInputStream fileInputStream=null;
HttpsURLConnection connection=null;
DataOutputStream dos = null;
FileInputStream fileInputStream=null;
HttpsURLConnection connection=null;
DataOutputStream dos = null;
try{
File fl=new File("D://abc.txt");
fileInputStream = new FileInputStream(fl);
url = new URL(url1);
connection = (HttpsURLConnection) url.openConnection();
connection.setReadTimeout(15*1000);
connection.setRequestProperty ("Authorization", "aaa " + "abc123ss556");
connection.setRequestProperty ("date_param", "123456");
connection.setRequestProperty ("userid", "aaa");
connection.setRequestProperty ("pwd", "111");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fl.getName());
String contentDisposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fl.getName() + "\"";
connection.setRequestProperty ("Content-Disposition", contentDisposition);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
dos = new DataOutputStream(connection.getOutputStream());
int responseCode = connection.getResponseCode();
int responseCode = connection.getResponseCode();
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fl.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int serverResponseCode = connection.getResponseCode();
System.out.println(serverResponseCode);
String serverResponseMessage = connection.getResponseMessage();
System.out.println(serverResponseMessage);
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
System.out.println("Server Response "+str);
}
inStream.close();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

How do I put HttpURLConnection into BroadcastReceiver OnReceive()?

I have an HttpURLConnection uploading a file, and my server then emails it. It works great. However, I don't want it in an Activity, I want it in the SMS receiver OnRecieve(), yet I can't seem to get it to work.
Please help? When I put the code into OnReceive(), it simply fails:(
Here's my code, it's quite simple:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
String fileName = "/mnt/sdcard/MyFile.dat";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File("/mnt/sdcard/MyFile.dat");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
Bunch of F%$kn losers on here sometimes, I must say. I'll go ahead and answer my OWN question again:
You cannot do an httpURLrequest in BroadcastReceiver(). It must be done in a service:
public class UploadService extends IntentService
{
public UploadService()
{
super("UploadService");
}
#Override
protected void onHandleIntent(Intent intent)
{
public void postForm(String phn, String mssg)
{
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
String fileName = "/mnt/sdcard/MyFile.dat";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File("/mnt/sdcard/MyFile.dat");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
}
}
Called with:
context.startService(new Intent(context, UploadService.class));

Upload File from Android to Tomcat

I'm trying to receive an upload from an android device in an Apache Tomcat webserver. The code for android seems correct however I'm having issues handling the data on server side.
This is the client:
public String uploadStorageFile(String appId, String pathToFile) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String storageUrl = url + "/" + appId + "/storage";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String serverResponseMessage = null;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToFile) );
URL url = new URL(storageUrl);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
return serverResponseMessage;
}
And this is server side:
#POST
#Consumes({ MediaType.MULTIPART_FORM_DATA })
#Produces({ MediaType.APPLICATION_JSON })
public Response uploadStorageFile(#Context UriInfo ui, #Context HttpHeaders hh, #FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("filename") FormDataContentDisposition fileDetail){
String uploadedFileLocation = fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The issue I'm facing is that fileDetail is null and so is uploadedInputStream, what am I doing wrong?
Thank you
The two file-related Objects in your uploadStorageFile method are actually bound to the same FormDataParam (i.e. - file).
Try changing your FormDataContentDisposition to the same param name as the InputStream.
EDIT: Sorry, I missed something else completely. The name of the form param you are sending is actually "uploadedFile", not file or filename. Change both of your FormDataParam's to be bound to the param named uploadedFile and they should no longer be null.

Categories

Resources