Iam developing a appliction for google glass using GDK and Im trying to upload my captured image using MultiPartEntity but i could not get it work for some reason i can't figure out because its not returning any error. As of now this is where I am.
Java
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
final File pictureFile = new File(picturePath);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("SERVER PATH");
try {
#SuppressWarnings("deprecation")
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(pictureFile));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
PHP CODE:
$response = array();
$file_upload_url = 'UPLOAD PATH';
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!';
}
echo json_encode($response);
?>
Any help would be much appreciated.
That's my code. it's working for me. You can send parameters and files with a progress bar using this code.
public class SendFile extends AsyncTask<String, Integer, Integer> {
private Context conT;
private ProgressDialog dialog;
private String SendUrl = "";
private String SendFile = "";
private String Parameters = "";
private String result;
public File file;
SendFile(Context activity, String url, String filePath, String values) {
conT = activity;
dialog = new ProgressDialog(conT);
SendUrl = url;
SendFile = filePath;
Parameters = Values;
}
#Override
protected void onPreExecute() {
file = new File(SendFile);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax((int) file.length());
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"
+ Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
String[] q = SendFile.split("/");
int idx = q.length - 1;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(SendUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=dosya; filename=\""
+ q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int boyut = 0;
while (bytesRead > 0) {
boyut += bytesRead;
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dialog.setProgress(boyut);
}
outputStream.writeBytes(lineEnd);
String[] posts = Bilgiler.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"
+ lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("TAG","result:"+result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Integer result1) {
dialog.dismiss();
};
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
and if you are sending to PHP you can use this
<?php
$file_path = "test/";
$username= $_POST["username"];
$password= $_POST["password"];
$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";
}
?>
Edit - 2:
you can call this AsyncTask like :
String FormData = "username=" + Session.getUsername()
+ "&password=" + Session.getPassword() ;
SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
SendIt.execute();
Related
Using this code I can upload files to the server. but I want to pass some other values to the php code to insert that value to database. but with the code I am using I couldn't make it
Here is the code i wrote for onClickListenter
public void onClick(View v) {
if(v== ivAttachment){
//on attachment icon click
showFileChooser();
}
if(v== bUpload){
final String arippe = "arippe";
//on upload button Click
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath, arippe);
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
}
Here is UploadFile function code
public int uploadFile(final String selectedFilePath, String arippe){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"arippe\""
+ lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(arippe);
dataOutputStream.writeBytes(lineEnd);
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
and here is the php code
$file_path = "uploads/";
$a = "areef";
$b = $_POST['arippe'];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
$c = $file_path;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
} else{
echo "fail";
}
$sql_query = "insert into users(name, user_name, user_pass) values('$a', '$b', '$c')";
mysqli_query($mysqli, $sql_query);
When I click upload button null value is posted to user_name
Well...you can use multipart request to upload data...
There are so many ways to upload data on server...
1- By using Volley networking library
https://developer.android.com/training/volley/index.html
2- by using retrofit library
http://square.github.io/retrofit/
Best way is to use Volley networking library..because Google Android recommended to use volley for any network operation.
Simple way is to use HttpUrlConnection class to upload data on server.
I am trying to upload images from android to php server The server is working all good for ios using objective c but in android I did not not know how to upload the images. I have tried the below code but the server returns message that (images are not in proper format or missing image file
ArrayList<File> imageFiles= new ArrayList<File>();
for(int i=0;i<mCameraDataList.size();i++) {
File f = new File(getFilesDir(),"image"+i+".jpg");
f.createNewFile();
Bitmap bitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeByteArray(mCameraDataList.get(i), 0, mCameraDataList.get(i).length),CommonMethods.getDeviceWidth(this), CommonMethods.getDeviceHeight(this), true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] bitmapdata = stream.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
imageFiles.add(f);
}
public static void postProduct(ArrayList<File> nImages) throws UnsupportedEncodingException {
MultipartEntityBuilder entity=MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("authenticity",new StringBody("1"));
entity.addPart("brand_id",new StringBody("1"));
entity.addPart("cat_id",new StringBody("2"));
entity.addPart("color_id1",new StringBody("2"));
entity.addPart("color_id2",new StringBody("3"));
entity.addPart("condition_id",new StringBody("3"));
entity.addPart("description",new StringBody("Bgvv"));
entity.addPart(Constants.KeyValues.DEVICE_ID,new StringBody(Constants.DEVICE_ID));
entity.addPart("images",new StringBody("images"));
entity.addPart("lon",new StringBody("74.344630"));
entity.addPart("lat",new StringBody("31.516762"));
entity.addPart("name_brand",new StringBody("2 puffs"));
entity.addPart("package_size",new StringBody("0"));
entity.addPart("selling_price", new StringBody("20"));
entity.addPart("title",new StringBody("My test"));
entity.addPart(Constants.KeyValues.UID,new StringBody(String.valueOf(CommonObjects.getUserProfile().getUid())));
for(int i=0;i<nImages.size();i++)
{
File f=new File(nImages.get(i).getAbsolutePath());
if(f.exists()){
entity.addPart(Constants.KeyValues.IMAGES, new FileBody(f, "image/jpeg"));
}
}
new SetDataToServer(Constants.NetworkServiceMethods.Product.POST_PRODUCT, entity, new SetDataToServer.SetDataNotifier() {
#Override
public void onDataReceived(boolean isError, String message, JSONObject jsonObj) {
ArrayList<String> postProductResult =new ArrayList<String>();
try {
Log.e("JSON",jsonObj.toString());
if (!jsonObj.isNull(Constants.KeyValues.DATA)) {
JSONObject jsonObjectData = jsonObj.getJSONObject(Constants.KeyValues.DATA);
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.CON_ID));
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.ORDER_ID));
}
} catch (JSONException e) {
isError = true;
message = "Sorry! Error occurred in data parsing";
}
productHandlerMethods.onPostProductResult(isError, message, postProductResult);
}
}).callServerToSetData();
}
Can any body tell what I am doing wrong.
Server side code
public function postproduct_post() {
$brand_id = $this->post('brand_id');
if ($brand_id == '') {
$brand_name = $this->post('name_brand');
if ($brand_name == '')
$this->create_error(-1);
$brand_id = $this->Mproduct->insertBrandName($brand_name);
} else {
if (!$this->Mproduct->_checkBrandId($brand_id))
$this->create_error(-15, 'brand_id');
}
$time = time();
$uid = $this->post('uid');
$cat_id = $this->post('cat_id');
$title = $this->post('title');
$description = $this->post('description');
$condition_id = $this->post('condition_id');
$authenticity = $this->post('authenticity');
$color_id1 = $this->post('color_id1', 0);
$color_id2 = $this->post('color_id2', 0);
$selling_price = $this->post('selling_price');
$package_size = $this->post('package_size');
$lat = $this->post('lat');
$lon = $this->post('lon');
if ($uid == '' || $cat_id == '' || $title == '' || $description == ''
|| $color_id1 == '' || $condition_id == '' || $authenticity == '') {
$this->create_error(-1);
}
if (!$this->Muser->_checkUid($uid))
$this->create_error(-10);
if (!$this->Mproduct->_checkCatId($cat_id))
$this->create_error(-15, 'cat_id');
if ($color_id1 > 0 && !$this->Mproduct->_checkColorId($color_id1)) {
$this->create_error(-15, 'color_id1');
}
if ($color_id2 > 0 && !$this->Mproduct->_checkColorId($color_id2)) {
$this->create_error(-15, 'color_id2');
}
$images = isset($_FILES['images']) ? $_FILES['images'] : null;
if ($images == null || count($images['name']) <= 0) {
$this->create_error(-21);
}
$this->load->model('Mfile');
if (!$this->Mfile->checkArrayImage($images)) {
$this->create_error(-13);
}
if (!$this->Mproduct->_checkConditionId($condition_id)) {
$this->create_error(-15, 'condition_id');
}
$params = array();
$params['owner_id'] = $uid;
$params['cat_id'] = $cat_id;
$params['title'] = $title;
$params['added'] = $time;
$params['brand_id'] = $brand_id;
$params['description'] = $description;
$params['is_sell'] = 1;
$params['size_id'] = 101;
$params['is_swap'] = 0;
$params['is_give'] = 0;
$params['color_id1'] = $color_id1;
$params['color_id2'] = $color_id2;
$params['condition_id'] = $condition_id;
$params['authenticity'] = $authenticity;
$params['lat'] = $lat;
$params['lon'] = $lon;
$params['last_activity'] = $time;
$params['last_comment'] = '';
$params['status'] = 1;
if ($selling_price != '')
$params['selling_price'] = $selling_price;
if ($package_size != '')
$params['package_size'] = $package_size;
$product_id = $this->Mproduct->insertProduct($params);
if ($product_id == -1) {
$this->create_error(-16);
}
$paths = $this->Mfile->saveArrayImage($images, $product_id, $time);
if (count($paths) <= 0) {
$this->create_error(-13);
}
$params = array();
$params['image'] = $this->Mfile->createThumbProduct($paths[0]);
$params['status'] = 1;
$this->Mproduct->updateAfterInsertProduct($product_id, $params);
$this->Mproduct->upItemInCat($cat_id);
$this->Mproduct->upItemInBrand($brand_id);
$this->Muser->upItemOfUser($uid);
$this->Mproduct->insertProductImage($product_id, $paths);
//$this->Mfeed->insertNotifyNewProduct($time, $uid, $product_id);
//$this->Mpush->createNotiAddProduct($uid, $product_id);
$uids = $this->Mproduct->getUidsFollowUser($uid);
$this->load->model('Mnotify');
$this->Mnotify->createNotifyMany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid));
$this->Mfeed->insertFeedWhenSell($time, $product_id);
$data = array();
$data['product_id'] = $product_id;
$this->create_success($data, 'Add success');
}
Try to upload the image via below service written in android, make sure that image path is correct in below code, place the image in sdcard :
public class MyService extends Service {
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
int serverResponseCode = 0;
String upLoadServerUri = null;
private static final String TAG = "com.example.ServiceExample";
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
sharedPref = getSharedPreferences("myfiles", MODE_PRIVATE);
/************* Php script path ****************/
upLoadServerUri = "http://myserver/uploadimage.php";
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
// long endTime = System.currentTimeMillis() + 10*1000;
// while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
uploadFile(sharedPref.getString(i + "", ""));
} catch (Exception e) {
}
}
// }
Log.i(TAG, "Service running " + currentId);
}
stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
}
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(Environment.getExternalStorageDirectory(),sourceFileUri);
File sourceFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + fileName);
if (!sourceFile.isFile()) {
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("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) {
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
}
I have a code snippet which helps me to get data from my mySQL database. It also works fine ! But now I want to add parameters for my sql query because until now this code only works for this :
mysql_query("SELECT * FROM tablename ORDER BY 5 DESC");
So everything is being outputed.For example I want to use a query like this :
mysql_query("SELECT * FROM tablename WHERE name LIKE "a%" ORDER BY 5 DESC");
That is my code snippet in Android :
public class get_data extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... params) {
String result = null;
InputStream is = null;
StringBuilder sb = null;
str_name_list = new ArrayList<String>();
str_nname_list = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Here is my Link");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// paring data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
int anz = jArray.length();
if (anz > 15)
anz = 15;
for (int i = 0; i < anz ; i++) {
json_data = jArray.getJSONObject(i);
str_name_list.add(json_data.getString("NAME"));
str_nname_list.add(json_data.getString("AGE"));
}
} catch (JSONException e1) {
} catch (ParseException e1) {
e1.printStackTrace();
}
return null;
}
}
I found out that I have to add it in HttpEntity but really dont know how without to destroy my code. Thanks in advance !
Before your HTTPResponse, try to add;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("your value", value));
and then;
httpPost.setEntity(new UrlEncodedFormEntity(params));
I hope this will work!
That's my code. it's working for me. You can send parameters and files with a progress bar using this code.
public class SendFile extends AsyncTask<String, Integer, Integer> {
private Context conT;
private ProgressDialog dialog;
private String SendUrl = "";
private String SendFile = "";
private String Parameters = "";
private String result;
public File file;
SendFile(Context activity, String url, String filePath, String values) {
conT = activity;
dialog = new ProgressDialog(conT);
SendUrl = url;
SendFile = filePath;
Parameters = Values;
}
#Override
protected void onPreExecute() {
file = new File(SendFile);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax((int) file.length());
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"
+ Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
String[] q = SendFile.split("/");
int idx = q.length - 1;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(SendUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=dosya; filename=\""
+ q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int boyut = 0;
while (bytesRead > 0) {
boyut += bytesRead;
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dialog.setProgress(boyut);
}
outputStream.writeBytes(lineEnd);
String[] posts = Bilgiler.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"
+ lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("TAG","result:"+result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Integer result1) {
dialog.dismiss();
};
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
and if you are sending to PHP you can use this
<?php
$file_path = "test/";
$username= $_POST["username"];
$password= $_POST["password"];
$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";
}
?>
Edit - 2:
you can call this AsyncTask like :
String FormData = "username=" + Session.getUsername()
+ "&password=" + Session.getPassword() ;
SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
SendIt.execute();
Im using the code below to upload an image to the server using java and PHP, i works fine, but i would like to resize the image before upload to the server, can some help me how to do that THANKS!!
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://192.168.0.15/UploadToServer.php";
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
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);
}
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 :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
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"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.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(MainActivity.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(MainActivity.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 php code 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";
}
? >
You could always try : http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/
Very easy to use.
then you just do :
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 150);
in the .resize you pass in the imgFile and then the size you want. I put 150 here just as an example
I'm trying to upload an image file on button click. I used the same php script for iOS and it seems to work fine. I have a added the code used to upload the file. What I suspect is that I'm not passing in the image file path correctly. I have infact added the saving image file method. I just save it as 'sign.jpeg'. I don't see the image on button click pointed to uploadfile(View view) method.
public void uploadFile(View view) {
try {
upload("sign.jpeg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
method implementing the file upload
public void upload(String selectedPath) throws IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = selectedPath;
String urlServer = "http://localhost:8888/uploadJava.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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\";name=\""
+ "sign.jpeg" + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
/*int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();*/
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
}
php script to upload the file
<?php
$target_path = "./images/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
error_log("Upload File >>" . $target_path . $_FILES['error'] . " \r\n", 3,
"Log.log");
error_log("Upload File >>" . basename($_FILES['uploadedfile']['name']) . " \r\n",
3, "Log.log");
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!";
}
?>
Saving picture taken from the camera after cropping
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
InputStream is = new ByteArrayInputStream(data);
Bitmap bmp = BitmapFactory.decodeStream(is);
bmp = Bitmap.createBitmap(bmp, 50, 200, bmp.getWidth() - 200, bmp.getHeight()/2);
saveImage("sign.jpeg", bmp, getApplicationContext());
try {
FileOutputStream fos;
fos= openFileOutput(fileName,Context.MODE_PRIVATE);
System.out.println(data);
fos.write(data);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}*/
finish();
//releaseCamera();
}
};
image saving method
private void saveImage(String filename, Bitmap b, Context ctx){
try {
ObjectOutputStream oos;
FileOutputStream out;// = new FileOutputStream(filename);
out = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(out);
b.compress(Bitmap.CompressFormat.PNG, 100, oos);
oos.close();
oos.notifyAll();
out.notifyAll();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And yes the Internet permission is added in the AndroidManifest.xml as below
<uses-permission android:name="android.permission.INTERNET"/>
Any idea what is wrong with the code above?
First do this:
File ourFile = new File(pathToOurFile);
int ourFileLength = (int)ourFile.length();
bufferSize = Math.min(ourFileLength, maxBufferSize);
And then I have to admit almost never having used available().
Written should be #bytesRead.
for (;;) (
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
if (bytesRead <= 0) {
break;
}
outputStream.write(buffer, 0, bytesRead);
}
And no notifyAll (is for Object locks/threads).
Since you are sending file to php via HTTP you might try this approach:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("yourdomain.com");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("uploadedfile", new FileBody(new File ("absolute_path_to_file")));
httpPost.setEntity(entity);
String resp = client.execute(httpPost, responseHandler);
} catch (IOException e) {
Log.d("log", e.getMessage(), e);
}
For this approach you will need httpmime and httpclient lib in your build path: http://hc.apache.org/downloads.cgi