I want to write an android app that can upload a file to a c sharp base web server.
So far I have no luck. I kept getting Address family not supported by protocol.
I've added INTERNET and WRITE_EXTERNAL_STORAGE in my manifest file.
Keep in mind that I run this in emulator.
Any idea or suggestion is really appreciated.
Thank you in advance
Justin The
anyway here is my code
Android - Uploader.java
package com.main;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class Uploader extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
TextView info;
private static final String TAG = "Uploader";
void setUrlAndFile(String urlString, String fileName, TextView info)
{
Log.d(TAG,"StartUploader");
this.info = info;
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
publishProgress(e.toString());
}
this.fileName = fileName;
}
synchronized void doUpload()
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.d(TAG,"lv1");
try
{
Log.d(TAG,"doUpload");
publishProgress("Uploading...");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition:form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer,0, bufferSize);
Log.d(TAG,"LvB");
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);
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
int ch;
Log.d(TAG,"LvC");
StringBuffer buff = new StringBuffer();
while((ch=is.read()) != -1)
{
buff.append((char)ch);
}
publishProgress(buff.toString());
dos.close();
Log.d(TAG,"lv2");
}
catch(Exception e)
{
publishProgress(e.toString());
}
}
#Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"lv1b");
return null;
}
protected void onProgressUpdate(String... progress)
{
this.info.setText(progress[0]);
}
}
and this is the main activity
package com.main;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class ReadWriteToPCActivity extends Activity
{
private static final String TAG = "ReadWriteToPCActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View upload = findViewById(R.id.Upload);
final EditText path = (EditText)findViewById(R.id.Path);
final TextView info = (TextView)findViewById(R.id.Info);
Log.d(TAG,"Start");
File fn = new File(Environment.getExternalStorageDirectory()+"/new.xml");
upload.setOnClickListener
(
new OnClickListener()
{
public void onClick(View v)
{
try
{
Log.d(TAG,"Step1");
WriteFile();
Uploader uploader = new Uploader();
//uploader.setUrlAndFile("http://192.168.0.123/receiver.aspx", path.getText().toString(), info);
uploader.setUrlAndFile("http://192.168.0.123/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/samplefile.txt", info);
//uploader.setUrlAndFile("http://10.0.2.2/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
//uploader.setUrlAndFile("http://192.168.0.123/personalfinance/ReceiveUpload.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
Log.d(TAG,"Upload." + Environment.getExternalStorageDirectory()+"/samplefile.txt;" + info.getText().toString());
uploader.execute();
}
catch(Exception e)
{
path.setText(e.toString());
Log.d(TAG,e.toString());
}
}
private void WriteFile()
{
try
{
Log.d(TAG,"Step 1 write file");
File newfile = new File(Environment.getExternalStorageDirectory() + "/samplefile.txt");
Log.d(TAG,"Step 2 write file");
if(!newfile.exists() && !newfile.createNewFile())
{
Log.d(TAG,"File exists");
}
Log.d(TAG,"cp3");
newfile.createNewFile();
Log.d(TAG,"Step 3 write file");
FileOutputStream fos = null;
Log.d(TAG,"Step 4 write file");
fos = new FileOutputStream(newfile);
Log.d(TAG,"Step 5 write file");
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Hello Android");
osw.flush();
osw.close();
FilePermission fp;
fp = new FilePermission(Environment.getExternalStorageDirectory()+"/samplefile.txt","read");
Log.d(TAG,"File created");
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
}
);
}
}
and last, this is my receiver file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonalFinance
{
public partial class receiver : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection uploadFiles = Request.Files;
HttpPostedFile postedFile = uploadFiles[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
}
Related
I have this code that allows me to select a file and upload it to a server.
Whenever I test it, it always says "File do not exist", I test it with different file explorer, but it's always the same message.
This is UploadFilesToServer.java
package com.example.hp.test;
/**
* Created by Haroun SMIDA on 8/8/2015.
*/
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hp.test.app.AppConfig;
public class UploadFilesToServer extends Activity implements OnClickListener {
private TextView uploadStatus;
private Button btnUploadFile;
private Button btnSelectFIle;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private static final int FILE_SELECT_CODE = 0;
/**
* ******* File Path ************
*/
private String uploadFilePath = null;
private String uploadFileName = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadfile);
btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
btnUploadFile.setOnClickListener(this);
btnSelectFIle = (Button) findViewById(R.id.btnSelectFile);
btnSelectFIle.setOnClickListener(this);
uploadStatus = (TextView) findViewById(R.id.uploadStatus);
/************* Php script path ****************/
upLoadServerUri = AppConfig.URL_UPLOAD;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSelectFile:
selectFile();
break;
case R.id.btnUploadFile:
dialog = ProgressDialog.show(UploadFilesToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("uploading started.....");
}
});
Log.i("File Path ", uploadFilePath);
Log.i("File Name ", uploadFileName);
uploadFile(uploadFilePath);
}
}).start();
;
break;
default:
break;
}
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
Log.i("File Uri ", sourceFileUri);
Log.i("File ", sourceFile.toString());
if (!sourceFile.exists()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("Source File not exist :"
+ uploadFilePath);
}
});
return 0;
} else {
try {
// 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("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_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) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
uploadStatus.setText(msg);
Toast.makeText(UploadFilesToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadFilesToServer.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("Got Exception : see logcat ");
Toast.makeText(UploadFilesToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
private void selectFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_SELECT_CODE);
uploadStatus.setText("Uploading file path :- '" + uploadFilePath+ "'");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
File fileToUpload = new File(uriString);
uploadFilePath = fileToUpload.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
}
}
}
}
}
What is the right method that allows me to get the right path for the selected file?
I am trying to upload image to php server. But it gives me
java.io.FileNotFoundException: http://*******.info/test.php
how can I solve this problem?
package com.androidexample.uploadtoserver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "service.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("uploading started.....");
}
});
doFileUpload();
Log.d("deneme", "buraya geldim i");
}
}).start();
}
});
}
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = uploadFilePath+uploadFileName;
// imageView1.setImageURI(Uri.parse(existingFileName));
Log.e("--adress Debug--",existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer ="";
String urlString = "http://w.****.info/test.php";
Log.d("deneme1", "buraya geldim i");
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// 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.
Log.d("deneme2", "buraya geldim i");
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=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
Log.d("deneme3", "buraya geldim i");
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);
Log.e("--burya geldimi --","");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("--b----------------mi --","");
}
Log.d("deneme4", "buraya geldim i");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug0", "error1: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug1", "error2: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug2", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug3", "error3: " + ioex.getMessage(), ioex);
}
}
}
}
}
my cat log
12-15 21:10:33.599: E/Debug3(9087): error3: http://***.info/test.php
12-15 21:10:33.599: E/Debug3(9087): java.io.FileNotFoundException: http://****.info/test.php
12-15 21:10:33.599: E/Debug3(9087): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer.doFileUpload(UploadToServer.java:140)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer.access$0(UploadToServer.java:66)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer$1$1.run(UploadToServer.java:57)
12-15 21:10:33.599: E/Debug3(9087): at java.lang.Thread.run(Thread.java:1019)
this is my server site code
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
I have made an app that is supposed to let me upload to a server but it only works on localhost. The online server I am using is ueuo.com (free). What might be a solution to this? Funny thing though, the server response code I get is 200.
Here is the app:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static final String JPEG_FILE_PREFIX = "img";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String FOLDER_NAME = "/idms/";
private String imageFileName = "";
Button btnUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeDirectory();
btnUpload = (Button) findViewById(R.id.button1);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
imageFileName = JPEG_FILE_PREFIX + timeStamp + JPEG_FILE_SUFFIX;
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName);
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 0);
}
});
}
public void makeDirectory() {
File dir = new File(Environment.getExternalStorageDirectory()
+ FOLDER_NAME);
if (!dir.exists()) {
dir.mkdir();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//String pathToOurFile = Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName;
// Upload the image to the server
new Thread(new Runnable() {
public void run() {
uploadFile();
}
}).start();
}
protected void uploadFile() {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName;
String urlServer = "http://idmstest.ueuo.com/upload_api/uploadtoserver.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.d("tester", pathToOurFile);
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
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=\""
+ pathToOurFile + "\"" + 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)
#SuppressWarnings("unused")
int serverResponseCode = connection.getResponseCode();
#SuppressWarnings("unused")
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
Log.d("tester", pathToOurFile);
} catch (Exception ex) {
// Exception handling
ex.printStackTrace();
Log.e("Upload file to server Exception", "Exception : "
+ ex.getMessage(), ex);
}
}
Here is the server-side php:
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
I have EditProfilAcitivity if i click imageview will select from gallery and no have problem. I have problem id i click button upload.
package net.drieanto.lagidimana;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.drieanto.lagidimana.library.AlertDialogManager;
import net.drieanto.lagidimana.library.ConnectionDetector;
import net.drieanto.lagidimana.library.UserFunctions;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EditProfileActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout, buttonsearch;
EditText editSearch;
private ListView list;
private ArrayAdapter<String> adapter;
private RibbonMenuView rbmView;
private Button test;
private ListView rbmListView;
private ListView rbmListView2;
private ArrayAdapter<String> adapt;
private ArrayAdapter<String> adapter2;
ListView list1;
LazyAdapter adapter1;
private static int RESULT_LOAD_IMAGE = 1;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
setContentView(R.layout.editprofile);
if (android.os.Build.VERSION.SDK_INT >= 11){
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.rgb(254,194,12)));
int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView actionBarTextView = (TextView)findViewById(actionBarTitleId);
actionBarTextView.setTypeface(null, Typeface.BOLD);
}
// Check if Internet present
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(EditProfileActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
/** Menu **/
rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
list = (ListView) findViewById(R.id.listView1);
ProgressDialog progressDialog = new ProgressDialog(
EditProfileActivity.this);
progressDialog.setMessage("Loading...");
EditProfileTask EditProfileTask = new EditProfileTask(
EditProfileActivity.this, progressDialog);
EditProfileTask.execute();
ImageView image = (ImageView) findViewById(R.id.gambarAvatar);
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
editSearch = (EditText) findViewById(R.id.search);
buttonsearch = (Button) findViewById(R.id.buttonsearch);
buttonsearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent search = new Intent(getApplicationContext(),
SearchActivity.class);
search.putExtra("data", editSearch.getText().toString());
search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(search);
finish();
}
});
/**
* This is an exmaple button it calls "hideMenu()" after each click
* similiar to the Facebook or Google+ apps
* **/
btnLogout = (Button) findViewById(R.id.buttonLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
/**
* This is the most important ListView, updating the main list in
* the Activity
**/
final String[] items_list = { "Home", "Follower", "Request", "View Profile" };
adapt = new ArrayAdapter<String>(EditProfileActivity.this,
android.R.layout.simple_list_item_1, items_list);
rbmListView = (ListView) findViewById(R.id.rbm_listview);
rbmListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent dashboard = new Intent(getApplicationContext(),
DashboardActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
break;
case 1:
Intent follower = new Intent(getApplicationContext(),
FollowerActivity.class);
follower.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(follower);
finish();
break;
case 2:
Intent request = new Intent(getApplicationContext(),
RequestActivity.class);
request.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(request);
finish();
break;
case 3:
Intent profil = new Intent(getApplicationContext(),
ProfilActivity.class);
profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profil);
// Closing dashboard screen
finish();
break;
default:
break;
}
rbmView.hideMenu();
}
});
rbmListView.setAdapter(adapt);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
Button upload = (Button)findViewById(R.id.imguploadbtn);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ImageUpload().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
selectedPath = getPath(selectedImage);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
final String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.gambarAvatar);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/*private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://git.drieanto.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// 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=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}*/
/**
* Allows users, even API < 5, to use the back button
*
* public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode)
* { case KeyEvent.KEYCODE_BACK: rbmView.hideMenu(); break; default: return
* super.onKeyDown(keyCode, event); } return true; }
*/
/**
* Options Menu<br>
* example toggle
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.test:
rbmView.toggleMenu();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public void showEditError(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
public void showEditSuccess(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://lagidimana.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// 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=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
}
}
upload.php file
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
i have chmod 777 folder uploads/
Error Message in logcat in bottom, but i don't understand with this error. Maybe you have same problem.
06-14 21:46:35.339: E/Debug(13682): File is written
06-14 21:46:53.339: E/Debug(13682): Server Response There was an error uploading the file, please try again!filename: target_path: uploads/
please help thank's
You are calling the function doFileUpload from the Main UI thread. Android does not allow you to make Network calls on the main thread.
Build an Asynctask and do the upload process of connecting to the network from another thread (in the doInBackground function).
I tried uploading an audio file from android client to server but I'm getting following error on server console:
java.io.FileNotFoundException:D:\temp\sdcard\recording20605.3gpp (The system cannot find the path specified)
("D:\temp" is where I'm trying to store file from client on my server i.e in temp folder in D drive of my pc).
Plz help
Here is the code for Client and server
SERVER CODE
// Import required java libraries
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 9000 * 1024;
private int maxMemSize = 6 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new
DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
------------------
CLIENT CODE
-----------------
package com.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class SampleclientActivity extends Activity {
private static final int SELECT_AUDIO = 2;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
openGalleryAudio();
}
public void openGalleryAudio(){
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_AUDIO)
{
System.out.println("SELECT_AUDIO");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_AUDIO Path : " + selectedPath);
doFileUpload();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 4*1024*1024;
String responseFromServer = "";
String urlString = "http://123.236.177.244:8085/myproject1/UploadServlet";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// 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=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
}
----------------------
AndroidManifest.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.client"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleclientActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Your filename contains an extra "\sdcard" which is trying to save the file in "sdcard" directory inside the "temp" directory. Ofcourse SDCARD is the directory not found on server so it is throwing exception. Either change the file name on runtime and remove "sdcard" from it or create the directory named "sdcard" inside "temp".
solution is:
private String filePath = "---your directory---"
private String filePath = "D:\temp\sdcard\"