Custom server response instead of OK . Android file upload - android

i'm creating an android application which upload files to web server . my code is working successfully but i'm getting server response message "OK" but i want it "success" or something else which i write on php echo but I am not sure how to do that... my php script is
<?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";
}
?>
and my code is...
public int uploadFile(String sourceFileUri) {
final String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
long sentBytes=0;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+filePath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+filePath);
}
});
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();
//Toast.makeText(getBaseContext(),serverResponseMessage, Toast.LENGTH_SHORT).show();
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://onsitesupport.info/diary/uploads/" + fileName.substring(fileName.lastIndexOf("/")+1);
messageText.setText(msg);
Toast.makeText(getBaseContext(), "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() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(getBaseContext(), "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() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(getBaseContext(), "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
}

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String stringResponse = sb.toString();
Log.d("response string:", stringResponse);

Related

Android post data along with file using multipart data

I am trying to send variable with HTTP post using multipart form data. I successfully sent file it uploading to server flawlessly but i am unable to send variables in the same request. Below is my sample code. Thanks in advance
public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {
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 = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ "" + uploadFileName);
}
});
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);
conn.setRequestProperty("name", name);
conn.setRequestProperty("price", price);
conn.setRequestProperty("category", category);
conn.setRequestProperty("album", albumid);
conn.setRequestProperty("artist_id", artistid);
conn.setRequestProperty("album_name", albumname);
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"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse,
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() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.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() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.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
}
I am sending the variable here
conn.setRequestProperty("uploaded_file", fileName);
conn.setRequestProperty("name", name);
conn.setRequestProperty("price", price);
conn.setRequestProperty("category", category);
conn.setRequestProperty("album", albumid);
conn.setRequestProperty("artist_id", artistid);
conn.setRequestProperty("album_name", albumname);
dos = new DataOutputStream(conn.getOutputStream());
Finally, after a lot of hit and trial i got my code working. Posting it as an answer for anyone who might want to do same task in android
public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {
String fileName = sourceFileUri;
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()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ "" + uploadFileName);
}
});
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);
conn.setRequestProperty("name", name);
conn.setRequestProperty("price", price);
conn.setRequestProperty("category", category);
conn.setRequestProperty("desc", description);
conn.setRequestProperty("album", albumid);
conn.setRequestProperty("artist_id", artistid);
conn.setRequestProperty("album_name", albumname);
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() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
sb.toString();
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+sb.toString();
messageText.setText(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse,
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() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.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() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.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
}
And for server side i am using php so i got all the key values in $SERVER, but beware all of ur keys will be capitalized with HTML concatenated with it automatically like i am sending album_name but on server it $_SERVER['HTTP_ALBUM_NAME'];
$albumname=$_SERVER['HTTP_ALBUM_NAME'];
I will suggest you to use okhttp. You can use it like that;
public void uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname, byte[] data) {
MediaType MEDIA_TYPE_MP3 = MediaType.parse("audio/mpeg");
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("uploaded_file", filename,
RequestBody.create(MEDIA_TYPE_MP3, data))
.addFormDataPart("name", name)
.addFormDataPart("price", price)
.addFormDataPart("category", category)
.addFormDataPart("album", album)
.addFormDataPart("category", category)
.addFormDataPart("artist_id", artistid)
.addFormDataPart("album_name", albumname)
.build();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(upLoadServerUri)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
#Override
public void onFailure(com.squareup.okhttp.Request request, IOException e) {
}
#Override
public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
}
});
}

get json response from httpurlconnection

I want to get Json response from httpurlconnection.
before I use httpclient and get httpresponse from this I get json.
but now I don't know how to get httpresponse from httpurlconnection.
I have tried to upload image by using this example:
http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106
Many thanks Yogendra but I'm not a pro in java can you convert this code to async http:
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 = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath );
runOnUiThread(new Runnable() {
public void run() {
messageText.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);
HttpResponse respons;
// 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);
StringBuilder builder = new StringBuilder();
builder.append(conn.getResponseCode())
.append(" ")
.append(conn.getResponseMessage())
.append("\n");
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
if (entry.getKey() == null)
continue;
builder.append( entry.getKey())
.append(": ");
List<String> headerValues = entry.getValue();
Iterator<String> it = headerValues.iterator();
if (it.hasNext()) {
builder.append(it.next());
while (it.hasNext()) {
builder.append(", ")
.append(it.next());
}
}
builder.append("\n");
}
Log.i("Response", builder.toString());
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = String.valueOf(conn.getContentEncoding());
// Log.i("uploadFile", "HTTP Response is : "
// + conn.getHeaderField("server") + ": " + 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/";
messageText.setText(msg);
Toast.makeText(UploadToServer.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() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.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() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.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
}
public class getServerDataAsync extends AsyncTask<String, Void, String> {
String 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;
String msg;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
fileName = arg0[0];
sourceFile = new File(arg0[0]);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" + uploadFilePath);
msg = "Source File not exist :" + uploadFilePath;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
fileName);
URL url = new URL(upLoadServerUri);
HttpResponse respons;
// 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);
StringBuilder builder = new StringBuilder();
builder.append(conn.getResponseCode()).append(" ")
.append(conn.getResponseMessage()).append("\n");
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.getKey() == null)
continue;
builder.append(entry.getKey()).append(": ");
List<String> headerValues = entry.getValue();
Iterator<String> it = headerValues.iterator();
if (it.hasNext()) {
builder.append(it.next());
while (it.hasNext()) {
builder.append(", ").append(it.next());
}
}
builder.append("\n");
}
Log.i("Response", builder.toString());
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = String.valueOf(conn
.getContentEncoding());
// Log.i("uploadFile", "HTTP Response is : "
// + conn.getHeaderField("server") + ": " +
// serverResponseCode);
if (serverResponseCode == 200) {
msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/";
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
msg = "MalformedURLException Exception : check script url.";
Log.e("Upload file to server", "error: " + ex.getMessage(),
ex);
} catch (Exception e) {
e.printStackTrace();
msg = "Got Exception : see logcat ";
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
} // End else block
return msg;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
messageText.setText(result);
}
}
call async class as
new getServerDataAsync().execute("source url");

Upload Files to MySQL Database using Android HTTP Post

Good day guys please help me, I'm already struggling for more than a month!!! I want to upload image to MYSQL database and nowhere else.
What I tried so far:
Uploading byte array to database=FAIL.(will not upload on server side)
Connect to mysql database and upload chars as strings=SUCCESS
Upload bytearray as a string to mysql=FAIL.(again won't upload on server side)
Please give me any full example or even source code how to upload image to mysql database or at least how to upload the link to that image to mysql database and as well as server side PHP code because I don't know php I just need to put in server side by example
Thank you very much beforehand guys, please help me!
Work for me!
Method in Class UploadtoServer extends Activiy:
public int uploadFile(String sourceFileUri) {
String lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
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 = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog1.dismiss();
Log.e("uploadFile", "O arquivo não existe :"
+uploadFilePath + "" + lstrArq);
runOnUiThread(new Runnable() {
String lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
public void run() {
messageText.setText("O arquivo não existe :"
+uploadFilePath + "" + lstrArq);
}
});
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 lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
String msg = "O arquivo " + lstrArq + " foi enviado com sucesso!";
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "O arquivo " + lstrArq + " foi enviado com sucesso!",
Toast.LENGTH_LONG).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog1.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Erro no servidor", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog1.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog1.dismiss();
return serverResponseCode;
} // End else block
}
Cod PHP in server:
<?php
$file_path = "mypatholder/";
$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";
}
?>
BYE!
If you want to upload a picture to server, follow the below code.
public ServerCommunication() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
}
public void uploadUserPhoto(File image) {
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("xyz", new StringBody("xyz"));
multipartEntity.addPart("xyz", new StringBody("xyz"));
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}
}
private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
#Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.d("UPLOAD", responseString);
return null;
}
}

file upload using httppost android

I have tried so many methods and answers that described on stack overflow and other blogs for uploading a file from my android app to my server but none of them worked for me.
I used httpclient4.3.3.jar,httpcore4.3.3.jar and httpmime4.3.3.jar
Am not getting any error messages and my app working fine. But not data coming in my server, am using php server and my server side code is bellow.
$file_path = "uploads/";
$file_path = $file_path.basename( $_FILES['file_data']['name']);
if(move_uploaded_file($_FILES['file_data']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
please give me any working samples or code with required libs. So many days am working on it.. please help me with a complete answer.
Try this.
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 = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
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;
messageText.setText(msg);
Toast.makeText(UploadToServer.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() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.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() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.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
}
You need to add following Jar in Your project , here i am giving you direct link for downloading.
httpclient-4.2.2.jar,
httpmime-4.0.jar

Capture sequential images in time-lapse

I am working with the camera on an Android device. I have captured some images and uploaded them to http.
I used an Intent to invoke an existing Android camera application
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_PIC_REQUEST);
I have Button:
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
int response = uploadFile("sdcad/" + myLocation
+ ".jpg");
}
}).start();
}
});
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "...";
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 = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
// connection to
// the URL
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);
bytesAvailable = fileInputStream.available(); // create a buffer of
// maximum size
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() {
tv.setText("File Upload Completed.");
Toast.makeText(getApplicationContext(),
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
// dialog.dismiss();
ex.printStackTrace();
Toast.makeText(getApplicationContext(), "MalformedURLException",
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
// dialog.dismiss();
return serverResponseCode;
}
Now I would like to to capture sequential images in time-lapse, upload these. How can I achieve this? Thanks.

Categories

Resources