How to send audio file to the server in android? - php

I am writing code to send audio file from android application to the server. The connection is working well, but I don't know how to make the file to save on the server.
My question is : How can I send audio file to server?
Can you please explain me what exactly should I do step by step? I think I am wrong somewhere on the part of encoding file..
public class UploadRecordingAsyncTask extends AsyncTask<String,Void, Void>{
String fileName;
String filePath;
String username;
public UploadRecordingAsyncTask(String filePath, String fileName, String username){
this.filePath = filePath;
this.fileName = fileName;
this.username = username;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try{
URL url = new URL(SERVER_ADDRESS + "UploadRecording.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
//past information
httpURLConnection.setDoOutput(true);
//get outputstreamwrite from http connection
OutputStream outputStream = httpURLConnection.getOutputStream();
//write down information
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, ENCODING_FORMAT));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//Encoding file part from here
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
InputStream inputStreamFile = new BufferedInputStream(fileInputStream);
int numOfBytes = inputStreamFile.available();
byte[] audioBytesFile = new byte[numOfBytes];
int i = inputStreamFile.read(audioBytesFile,0,numOfBytes);
String audioString = Base64.encodeToString(audioBytesFile, 0);
inputStreamFile.close();
//encode data before sending
String data = URLEncoder.encode("filename", ENCODING_FORMAT) + "=" + URLEncoder.encode(fileName, ENCODING_FORMAT) + "&" +
URLEncoder.encode("owner", ENCODING_FORMAT) + "=" + URLEncoder.encode(username, ENCODING_FORMAT) + "&" +
URLEncoder.encode("encodedfile", ENCODING_FORMAT) + "=" + URLEncoder.encode(audioString, ENCODING_FORMAT) + "&";
//write data into buffer writer
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//input stream to get response from the server
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
}
}
And on the server I have php file :
<?php
require "init.php";
if(isset($_POST["encodedfile"])){
$filename = $_POST["filename"];
$owner = $_POST["owner"];
$decoded_string = base64_decode($_POST["encodedfile"]);
$path = "recordings/".$filename;
//new file of audio
$file = fopen($path, 'wb');
to_write_file = fwrite($file, $decoded_string);
fclose($file);
$query = "INSERT INTO Recording (filename, owner, encodedfile) VALUES (?,?,?)";
if($stmt = mysqli_prepare($connectDB, $query)){
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'sss', $filename, $owner, $decoded_string);
/* execute line*/
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($connectDB);
}
?>

Related

How to upload an image from android to php using asynctask

everyone. I am stuck on this project I am working on. I want to be able to upload an image from the android gallery, encode that image to a base64 string and send to PHP web service, as a get variable, then decode the image from the other end and do with it as I wish.
So far I am able to select the image, from the gallery and even encode to base64 string and storing in android preference.
The problem is, I think that not all the string is being sent to the PHP service (Some is truncated).
Why do I think so? My Log.d showed me different strings when dumped at different locations.
The code that gets the image and encodes is:-
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}
private String onSelectFromGalleryResult (Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
byte[] imageBytes = byteArrayOutputStream.toByteArray() ;
Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;
return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
} else {
return null ;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit() ;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
/*Here we handle the image gotten from the gallery*/
String encodedGalleryImage = onSelectFromGalleryResult(data);
editor.putString("userEncodedGalleryImage" , encodedGalleryImage);
} else if (requestCode == 0) {
/*Here we handle the image that was take using the camera*/
}
editor.apply();
}
}
Here we call the asynctask class
private void callAsynctask () {
SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;
Log.d("callingEncodedImage" , userQuestionAttachement) ;
}
The problem I have is that the log from Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ; is different from Log.d("callingEncodedImage" , userQuestionAttachement) ;
There both have same beginning, but different endings. I expect to see the same characters.
Can someone please help me sort it out?
In Android,
new UploadFileAsync().execute("");
private class UploadFileAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String sourceFileUri = "/mnt/sdcard/abc.png";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (sourceFile.isFile()) {
try {
String upLoadServerUri = "http://website.com/abc.php?";
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// 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("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// 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();
if (serverResponseCode == 200) {
// messageText.setText(msg);
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
// recursiveDelete(mDirectory1);
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
}
// dialog.dismiss();
} // End else block
} catch (Exception ex) {
// dialog.dismiss();
ex.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
In Php,
<?php
if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
$uploads_dir = './';
$tmp_name = $_FILES['bill']['tmp_name'];
$pic_name = $_FILES['bill']['name'];
move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
}
else{
echo "File not uploaded successfully.";
}
?>
To upload image using Multipart follow the following steps:
Download httpmime.jar file and add it in your libs folder.
Download http client.jar file and add it in your libs folder.
Call the following method either from a background thread or an AsyncTask.
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"YOUR SERVER URL");
ByteArrayBody bab = new ByteArrayBody(data, "YOUR IMAGE.JPG");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("IMAGE", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}

Base64 encoding product different result

I am working on android project which can upload image from user's phone galery. The method i use to upload the image is to encode the image to base64 in android and send it to PHP files on server, then the PHP file decodes it then put it on server.
But the problem is the result of PHP decoding is different with the original image. Although the image is still working, but i am afraid sometimes it's gonna be a bug :D..
How to solve it?
Class UploadImageCatalog
#Override
protected String doInBackground(String... params) {
String urlAPI = params[0];
String id = params[1];
String imageByte = params[2];
try {
URL url = new URL(urlAPI);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setReadTimeout(15000);
urlCon.setConnectTimeout(15000);
urlCon.setDoOutput(true);
urlCon.setRequestMethod("POST");
OutputStream os = urlCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
String postData = URLEncoder.encode("id", "UTF-8")+"="+URLEncoder.encode(id, "UTF-8")+"&"+
URLEncoder.encode("imageByte", "UTF-8")+"="+URLEncoder.encode(imageByte, "UTF-8");
bw.write(postData);
bw.flush();
bw.close();
osw.close();
os.close();
urlCon.connect();
int responseCode = urlCon.getResponseCode();
if (responseCode == HTTP_OK) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String responseString = br.readLine();
br.close();
isr.close();
is.close();
return responseString;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Method getStringImage()
private String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
Mehthod to upload image
btSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (updateImage) {
new UploadImageCatalog(ViewProductActivity.this)
.execute(SERVER_URL+"/project/katalogmukenalukis/uploadimage.php",
String.valueOf(idToView), getStringImage(imageLoadedBitmap));
} else {
updateData();
}
}
});
uploadimage.php
<?php
$id = $_POST['id'];
$imageByte = $_POST['imageByte'];
$target = __DIR__."/asset/".$id;
if (file_exists($target)) {unlink($target);}
if (file_put_contents($target, base64_decode($imageByte))) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false, "message" => ""));
}
?>

Upload a file from Android to the server via PHP

Can anyone help me to make my code work, i.e. upload a file from Android to the server via PHP? I tried it in many different ways but it won't work. I get HTTP Response 200 but the files aren't uploaded on server.
The PHP script I'm using for upload is:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>
I also tried using multipart from Httpmime 4.0 but it wont work.
public void uploadFile(String path)
{
File file = new File(path);
try {
HttpClient client = new DefaultHttpClient();
String postURL = upLoadServerUri;
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_file", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE Wahaj: ","Code : "+ EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath());
Here fileUri.getPath() local image location.

Data getting inserted multiple times - android, php

In my project, I'm sending data from an android device and it is inserted into a database using a php script. But the same data is inserted twice. (please see here)
What is wrong with my code?
Android:
try {
String data=URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(Name, "UTF-8");
data+="&"+URLEncoder.encode("family", "UTF-8")+"="+URLEncoder.encode(Family, "UTF-8");
data+="&"+URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(City, "UTF-8");
data+="&"+URLEncoder.encode("ostan", "UTF-8")+"="+URLEncoder.encode(Ostan, "UTF-8");
data+="&"+URLEncoder.encode("tel", "UTF-8")+"="+URLEncoder.encode(Tel, "UTF-8");
data+="&"+URLEncoder.encode("sef", "UTF-8")+"="+URLEncoder.encode(sef1, "UTF-8");
data+="&"+URLEncoder.encode("bod", "UTF-8")+"="+URLEncoder.encode(bodjeh1, "UTF-8");
data+="&"+URLEncoder.encode("tab", "UTF-8")+"="+URLEncoder.encode(tabgh, "UTF-8");
data+="&"+URLEncoder.encode("img", "UTF-8")+"="+URLEncoder.encode(imgs, "UTF-8");
data+="&"+URLEncoder.encode("imgf", "UTF-8")+"="+URLEncoder.encode(fimage, "UTF-8");
URL link=new URL(MainActivity.url+"/app/order.php");
URLConnection con=link.openConnection();
con.setDoOutput(true);
OutputStreamWriter wrw=new OutputStreamWriter(con.getOutputStream());
wrw.write(data);
wrw.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
String l="";
while((l=br.readLine())!=null){
sb.append(l);
}
r=sb.toString();
br.close();
Code for insertion - php
$name=$_POST['name'];
$family_name=$_POST['family'];
$city=$_POST['city'];
$ostan=$_POST['ostan'];
$tel=$_POST['tel'];
$comment=$_POST['sef'];
$bod=$_POST['bod'];
$tab=$_POST['tab'];
$img=$_POST['img'];
$imgf=$_POST['imgf'];
$sql="INSERT INTO `customer_table`(`id`, `name`, `family_name`, `city`, `ostan`, `tel`, `comment`,`bodjeh`,`tabagheh`,`imag_f`,`image`)
VALUES ('','$name','$family_name','$city','$ostan','$tel','$comment','$bod','$tab','$imgf','$img')";
Please use below method to send data to server
First convert your request json into simple map like
Map<String, String> map = new HashMap<>();
map.put("name", Name);.....so on
Then use below method to call the Webservice.
private JSONObject sendRequest(String urlString, Map<String, String> map, String fileKey, File file) {
StringBuilder strData= null;
JSONObject resObj = null;
try {
Log.i("Send request", urlString+"="+map);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(map == null)
{
map = new HashMap<>();
}
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (HashMap.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
reqEntity.addPart(k, new StringBody(v));
}
if(file != null && !TextUtils.isEmpty(fileKey))
{
FileBody filebody = new FileBody(file, "image/*");
reqEntity.addPart(fileKey, filebody);
}
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sResponse;
strData = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
strData = strData.append(sResponse);
}
}
if(strData != null)
resObj = new JSONObject(strData.toString());
} catch (Exception e) {
e.printStackTrace();
}
return resObj;
}
As your php code you need to do :
$result = mysql_query($sql);
if(count($result) > 0)
{
echo "1";
}else
{
echo "0";
}

Android AsyncTask Upload Files

I want upload a number of files that are stored on the android device but it seems to be stuck in the doInBackground Method of AsyncTask. I get no errors. The Dialog popsup and stays active i eliminated the dialog and no effect. The other part of my project is to decode the json files I uploaded and store them in a database but thats for later.
/********************UPLOAD GPSDATA*************************************/
class UploadGpsData extends AsyncTask<Void, Void, Void>{
NetworkInfo net;
MainActivity uActivity;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String folderPath;
String arrayOfFiles[];
File root;
File allFiles;
String urlServer = "http://urluploadscriptaddress.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
URL url;
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
Log.d(" UploadGpsData","onPreRequest");
pDialog.setMessage("Uploading GPS Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Log.d(" UploadGpsData","doInBackground");
root = Environment.getExternalStorageDirectory();
//pathToOurFile = root.getAbsolutePath()+"/Beagle Data/07-09-2013_16-21-30.json";
folderPath = root.getAbsolutePath()+"/Beagle Data/";
allFiles = new File(folderPath);
arrayOfFiles = allFiles.list();
for(int i = 0; i < arrayOfFiles.length; i++){
Log.d("File Names", arrayOfFiles[i].toString());
//File filename = new File(arrayOfFiles[i].toString());
try {
url = new URL(urlServer);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
try{
FileInputStream fileInputStream = new FileInputStream(new File(folderPath+arrayOfFiles[i].toString()) );
try {
outputStream = new DataOutputStream( connection.getOutputStream() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + folderPath+arrayOfFiles[i].toString() +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//int serverResponseCode = connection.getResponseCode();
//String serverResponseMessage = connection.getResponseMessage();
// Responses from the server (code and message)
//serverResponseCode = connection.getResponseCode();
//serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch(Exception e){
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute() {
Log.d(" UploadGpsData","onPost");
pDialog.dismiss();
txtUploadStatus = (TextView) findViewById(id.txtUploadStatus);
txtUploadStatus.setText("Upload Achieved");
}
}
/********************END OF UPLOADGPSDATA*************************************/
PHP Script below: The error log is empty so I am assuming its stuck on the android application
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$file = basename( $_FILES['uploadedfile']['name']);
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
?>
You do not implement the #Override onPostExecute.
Modify your onPostExecute assignature with this:
#Override
protected void onPostExecute(Void result) {
This will resolve your problem.
What was happening:
You are not overriding the OnPostExecute AsyncTask method, was creating a new one.
You are missing the params for onPostExecute() may be one problem
#Override
protected void onPostExecute(Void result) {
Even though you aren't returning anything to it from doInBackground() you still need this to be the AsyncTask method. If this doesn't fix it then please also post how you are calling it and explain if you have set breakpoints anywhere to see what it is doing.
You "manipulate" UI in a no-UI thread.
Try to comment all your code related to UI, it should work.
You can use
Context.runOnUiThread(new Runnable() ....
In order to do UI stuff.

Categories