Post parameter to PHP file - java

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();

Related

How to upload file and pass other parameters to the web server using DataOutputStream in Android Studio

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.

FileNotFoundException when clicking on button to upload audio

I am uploading audio on soundcloud server but when i click upload button it throws FileNotFoundException.After uploading a response from server has to be generated.plss help me guys. please correct me if i am making mistake somewhere.
There are 2 situation in which upload function is performed.
1.Recording of only one page story audio and uloding it.(in this case the audio is being uploade).
2. Recording of more than one page story in which after uploading of 1st page audio the 2nd page will come as response from my server.(In this case its throwing FileNotFound Exception).
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"Reponse Check for sound upload login :"+response);
// Log.d(TAG,"Object Check :"+json);
try {
JSONObject json = new JSONObject(response);
access_token = json.getString("access_token");
expires_in = json.getString("expires_in");
refresh_token = json.getString("refresh_token");
// doFileUpload();
new AsyncTaskRunner().execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Error Response Check :" + error);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", client_id);
params.put("client_secret",client_secret);
params.put("grant_type",grant_type);
params.put("username",username);
params.put("password",user_password);
Log.d(TAG, "Params :" + params);
return params;
}
}; AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
});
}
private void mergeAudioFiles(){
try {
File tempFolder = new File(mRawAudioFolder.getPath());
Movie[] movies = new Movie[tempFolder.listFiles().length];
int i = 0;
for (File saveTempFile : tempFolder.listFiles()) {
try {
movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
final Movie finalMovie = new Movie();
List<Track> audioTracks = new ArrayList<>();
for (Movie movie : movies) {
for (Track track : movie.getTracks()) {
}
}
finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
final Container container = new DefaultMp4Builder().build(finalMovie);
mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
final FileOutputStream fos = new FileOutputStream(mergedFile);
FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
container.writeContainer(fc);
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createAudioFolder() {
File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
mRawAudioFolder = new File(movieFile, "Temp");
mAudioFolder = new File(movieFile, "The Tagore Project");
if (!mAudioFolder.exists()) {
mAudioFolder.mkdirs();
}
if (!mRawAudioFolder.exists()) {
mRawAudioFolder.mkdirs();
}
}
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
public void forwardtoOurServer() {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Audio Upload Response Check :" + response);
Log.d(TAG,"Object Check :"+response);
try {
JSONObject json = new JSONObject(response);
String code = json.getString("code");
if (String.valueOf(code).equals("200")) {
JSONObject upload = json.getJSONObject("upload");
JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
String content = Composition.getString("content");
String pageno = Composition.getString("pageno");
String tocid = Composition.getString("table_of_content_id");
String wrd_count = Composition.getString("wordcount");
String tocName = TableofContents.getString("name");
} else {
String errorMsg = json.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error Response Check :" + error);
}
}) {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("data[Booking][id]",bookingId);
params.put("data[Booking][contributor_id]",contributor_id);
params.put("data[Booking][table_of_content_id]",tocId);
params.put("data[Booking][cdn_id]",vs_cdn_id);
params.put("data[Booking][secret_token]",secret_token);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date now = new Date();
String strDate = sdf.format(now);
params.put("data[Booking][uploaded_on]",strDate);
Log.d(TAG, "Params :" + params);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("UUID", device_uuid);
headers.put("APPID", "2A192A0C22");
headers.put("USERID", "1");
headers.put("PLATFORM", "Andriod");
headers.put("APP_REQUEST", "1");
headers.put("PLATFORMVERSION",androidOS);
return headers;
}
};
AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(RecordComposition.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(RecordComposition.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
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 = 1*1024*1024;
String responseFromServer = "";
String urlString = "https://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(mergedFile);
// open a URL connection to the Servlet
URL url = new URL (urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.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() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+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);
}
dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
try {
BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
Log.e("Debug","Before while");
while (( str = inStream.readLine() ) != null)
{
Log.e("Debug","Server Response "+str);
JSONObject response = new JSONObject(str);
vs_cdn_id = response.getString("id");
secret_token = response.getString("secret_token");
forwardtoOurServer();
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
Log:
File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
error: https://api.soundcloud.com/tracks
java.io.FileNotFoundException: https://api.soundcloud.com/tracks
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Give permission in menifest...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this on your code in your Activity class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> types = new ArrayList<>();
//add item to manes and types array
ListViewAdapter customList = new ListViewAdapter(this, names, types);
list = (ListView) findViewById(R.id.lv);
list.setAdapter(customList);
}
This is ListViewAdapter class
public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;
public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
super(context, R.layout.item_rating_rows, names);
this.context = context;
this.names = names;
this.types = types;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
Button btn = (Button) listViewItem.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("__onclick", "" + view.getId());
}
});
return listViewItem;
}
}

Upload Image On Php Server In Android Programically

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
}
}

Android Upload image using MultipartEntity using GDK

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();

Java file uploading using PHP : Not working

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

Categories

Resources