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.
Related
I have a cross platform app built using Monaca/Onsen UI and AngularJS.
The app allows users to take images (photos) and this is working as intended.
Next, I want to upload the images to my server for storage and future use.
I have the app image capture working as intended and I have implemented a PHP solution on the server that appears to be working, but I cant seem to see the images.
My app code for capture and upload looks as follows (at the moment I just access the image library and select images for testing - rather than capturing them - but both solutions working):
$scope.takePicture = function getImage() {
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://mysite/public/api/savephotos.php", function (result) {
alert("Success: " + JSON.stringify(result)); // Success: {"bytesSent":42468,"responseCode":200,"response":"","objectId":""}
}, function (error) {
alert("Fail: " + JSON.stringify(error));
}, options);
}
From the success response it seems that images are being sent, but when I check the folder where the images are supposed to be saved to (C:\xampp\htdocs\public\api\upload), the folder is empty. The server side details are Sximo template using Laravel framework hosted on AWS.
The PHP code that handles the server side saving looks as below:
<?php
// Connect to Database
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'myDB';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Allow Headers
header('Access-Control-Allow-Origin: *');
$new_image_name = urldecode($_FILES["file"]["name"]).".jpg";
// Move files into upload folder
move_uploaded_file($_FILES["file"]["tmp_name"], 'C:\xampp\htdocs\public\api\upload'.$new_image_name);
mysqli_close($mysqli);
However, the C:\xampp\htdocs\public\api\upload is empty - with no images sent to it. I do have a file called uploadimage that has been sent to the directory *C:\xampp\htdocs\public\api* that appears to be updated with each test - but this is a empty (0kb) file.
Where am I going wrong with this?
This is the asynktask that I use to send image from the gallery app to server
public static class requestPostReportPhoto extends AsyncTask<String, Void, String> {
Bitmap image;
String JSON_STRING;
#Override
protected void onPreExecute(){
String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";
image = BitmapFactory.decodeFile(fileUrl);
}
#Override
protected String doInBackground(String... params) {
String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection connection = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String response = "Error";
String urlString = "yourUrlServer";
try {
File file = new File(fileUrl);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + "PHOTONAME" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d("MediaPlayer", "Headers are written");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
StringBuilder responseSB = new StringBuilder();
int result = connection.getResponseCode();
BufferedReader br;
// 401 - 422 - 403 - 404 - 500
if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500)
{
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
else {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ( (JSON_STRING = br.readLine()) != null)
responseSB.append(JSON_STRING+ "\n");
Log.d("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
br.close();
response = responseSB.toString().trim();
} catch (IOException ioe) {
Log.d("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("SERVER RESPONSE ->",result)
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
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());
}
}
I'm working on a social app and I want to upload an image in the database, I tried a code and it worked. The file is in my folder but the problem is that the path couldn't get to the Mysql database I figured out that $_FILES['uploaded_file']['name'] is empty but I don't know how to solve this.
AddStatus.java :
public class AddStatus extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pDialog;
EditText status;
Button send,upload_img;
String user_id;
private TextView messageText;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String imagepath=null;
JSONParser jsonParser = new JSONParser();
private static final String upLoadServerUri = "http://192.168.1.10/social/addstatus.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_status);
ImageView img= new ImageView(this);
status =(EditText)findViewById(R.id.edt_status);
send = (Button)findViewById(R.id.btn_send);
upload_img = (Button) findViewById(R.id.btn_img);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
send.setOnClickListener(this);
upload_img.setOnClickListener(this);
final Intent callingIntent = getIntent();
user_id = callingIntent.getStringExtra("user_id");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
dialog = ProgressDialog.show(AddStatus.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
String stat = status.getText().toString();
Long ts = System.currentTimeMillis();
String time = ts.toString();
new addStatus().execute(stat,user_id,time);
break;
case R.id.btn_img:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
break;
default:
break;
}
}
#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(AddStatus.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(AddStatus.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(AddStatus.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
public void onPause() {
super.onPause();
if (pDialog != null)
pDialog.dismiss();
}
class addStatus extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddStatus.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String status = args[0];
String user_id = args[1];
String time = args[2];
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("status", status));
params.add(new BasicNameValuePair("user_id", user_id));
params.add(new BasicNameValuePair("time", time));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
upLoadServerUri, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(AddStatus.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
addStatus.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$response = array();
$target_path = "";
$file_upload_url = 'http://' . '192.168.1.10' . '/' . 'social' . '/' . $target_path;
if (isset($_FILES['uploaded_file']['name'])) {
$target_path = $target_path . basename($_FILES['uploaded_file']['name']);
$response['file_name'] = basename($_FILES['uploaded_file']['name']);
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['uploaded_file']['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['uploaded_file']['name']);
$path = $file_upload_url . basename($_FILES['uploaded_file']['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!F';
}
if (isset($_POST['user_id']) && isset($_POST['status']) && isset($_POST['time'])){
$status = $_POST['status'];
$user_id = $_POST['user_id'];
$time = $_POST['time'];
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO posts(user_id,text,time,image) VALUES('$user_id','$status','$time','$path')");
if ($result) {
$response["success"] = 1;
$response["message"] = "User created";
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "Registration failed";
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I hope you can help me with this issue. Thanks.
I know how to upload the file from android and I am able to do it by using the following code
private void doFileUpload(MessageModel model) {
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;// 1 MB
String responseFromServer = "";
String imageName = null;
try {
// ------------------ CLIENT REQUEST
File file = new File(model.getMessage());
FileInputStream fileInputStream = new FileInputStream(file);
AppLog.Log(TAG, "File Name :: " + file.getName());
String[] temp = file.getName().split("\\.");
AppLog.Log(TAG, "temp array ::" + temp);
String extension = temp[temp.length - 1];
imageName = model.getUserID() + "_" + System.currentTimeMillis()
+ "." + extension;
// open a URL connection to the Servlet
URL url = new URL(Urls.UPLOAD_VIDEO);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ imageName + "\"" + lineEnd);
Log.i(TAG, "Uploading starts");
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) {
// Log.i(TAG, "Uploading");
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
AppLog.Log(TAG, "Uploading Vedio :: " + imageName);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
Log.i(TAG, "Uploading ends");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE ----------------
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
try {
final JSONObject jsonObject = new JSONObject(str);
if (jsonObject.getBoolean("success")) {
handler.post(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
handler.post(new Runnable() {
#Override
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
model.setMessage(imageName);
onUploadComplete(model);
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
manageQueue();
}
the code is working perfectly for short videos but it is not uploading the large files and I no hint why .:(
I know its a bad practice to just ask that why my code is not working but here I am asking why is the code behaving different for large files.
I also check other answers on StackOverFlow but didn't find any flaw in my code.
Thanks
You can try HttpClient jar download the latest HttpClient jar, add it to your project, and upload the video using the following method:
private void uploadVideo(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )
Try Android Asynchronous Http Client library.
AsyncHttpClient client = new AsyncHttpClient();
File myFile = new File("/path/to/video");
RequestParams params = new RequestParams();
try {
params.put("video", myFile);
} catch(FileNotFoundException e) {}
client.post("POST URL",params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
Try volley, add library in your project and enjoy, its fast and easy to integrate.
final AbstractUploadServiceReceiver uploadReceiver = new AbstractUploadServiceReceiver() {
#Override
public void onProgress(String uploadId, int progress) {
Log.i("", "upload with ID " + uploadId + " is: " + progress);
}
#Override
public void onError(String uploadId, Exception exception) {
String message = "Error in upload with ID: " + uploadId + ". " + exception.getLocalizedMessage();
Log.e("", message, exception);
}
#Override
public void onCompleted(String uploadId, int serverResponseCode, String serverResponseMessage) {
String message = "Upload with ID " + uploadId + " is completed: " + serverResponseCode + ", "
+ serverResponseMessage;
Log.i("", message);
}
};
uploadReceiver.register(context);
final docUploadParams item="yourdocUploadParam";
sendUploaderRequest(context, URLtoUpload, item);
public void sendUploaderRequest(Context context,String url,docUploadParams item)
{
final UploadRequest request = new UploadRequest(context,url);
//in case of image
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile( ).getName() , ContentType.IMAGE_JPEG);
//in case of audio
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.AUDIO_M3U);
//in case of video
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.VIDEO_MPEG);
//custom parameters if any
request.addParameter("userId",item.userID);
//progress on notification bar
request.setNotificationConfig(R.drawable.ic_launcher,
"Uploading Files",
"Upload in Progress",
"Upload Completed Successfully",
"Error in Uploading",
false);
try {
UploadService.startUpload(request);
} catch (Exception exc) {
exc.printStackTrace();
}
}
Within an Activity in my Android Application I am attempting to upload 4 text files from the storage on device to a server using a PHP script.
These files are generated in the previous activity whilst playing a game.
However when I try to upload them i get the following exception message from my code:
"Source file not exist" then it shows the path to the filename that should of been uploaded
I know that the files are being properly generated as I can see them on the devices storage. I also know that the upload to server functionality works as I have tested it with a file that was created a few days ago.
Basically I am wondering:
Are the files fully created in previous activity before the next activity tries to upload them? I.e. how long does it take to write to storage?
Would delaying the thread that carries out upload functionality solve the problem?
Activity where files are uploaded: (note: file names passed as intent extras to next activity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mathsgameresults);
initialiseVars();
setAllTextViews();
messageText = (TextView)findViewById(R.id.mathsresultsservertext);
messageText.setText("Uploading file path :- '/storage/sdcard0/files/"+fileNameRaw
+"','/storage/sdcard0/ files/"+fileNameEEGPower+"','/storage/sdcard0/files/"+fileNameMeditation+"','/storage/sdcard0/files/"+fileNameAttention+"' ");
//url to php script on server
upLoadServerUri = " my url in here (not shown)";
//remove this if not wanted to show.
dialog = ProgressDialog.show(MathsGameResults.this, "", "Uploading files...", true);
//logic to upload files in new thread
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + fileNameRaw);
uploadFile(uploadFilePath + "" + fileNameEEGPower);
uploadFile(uploadFilePath + "" + fileNameMeditation);
uploadFile(uploadFilePath + "" + fileNameAttention);
}
}).start();
}
public int uploadFile(String sourceFileUri) {
final String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
final File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ sourceFileUri);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ fileName);
}
});
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();
final String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
//server responsecode 200 means upload successful
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = serverResponseMessage + "File Upload Completed.\n\n "
+fileName;
messageText.setText(msg);
Boolean isDel = sourceFile.delete();
if(isDel)
{
Toast.makeText(MathsGameResults.this, "File Upload Complete. And Deleted.",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MathsGameResults.this, "File Upload Complete. And NOT Deleted.",
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(MathsGameResults.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
final String d = e.getMessage() + " " + e.getStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText(d + " Got Exception : see logcat ");
Toast.makeText(MathsGameResults.this, "Got Exception : see logcat ",
Toast.LENGTH_LONG).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
EDIT:
Previous Activity where files are created:
Method that creates file (all 4 are identical):
/**
* Method used to save Raw data to a file on phone
*
* #param data
*/
public void writeToFileRawData(String data) {
// creating the file where the contents will be written to
File file = new File(dir, fileNameRaw + ".txt");
FileOutputStream os;
try {
boolean append = true;
os = new FileOutputStream(file, append);
String writeMe = data + "\n";
if (isHeaderDateRaw) {
os.write(headerDateRaw.getBytes());
isHeaderDateRaw = false;
}
if (isHeaderRawValues) {
os.write(headerRawValues.getBytes());
isHeaderRawValues = false;
}
os.write(writeMe.getBytes());
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Path were files are saved and creating file name:
// code relating to saving to file
File sdCard = Environment.getExternalStorageDirectory();
dir = new File(sdCard.getAbsolutePath() + "/files/");
dir.mkdir();
//creating file name
fileNameRaw = "MathsGame-Raw-" + timestamp + android.os.Build.SERIAL;
Saving data to file using handler:
case TGDevice.MSG_RAW_DATA:
headerRawValues = order("Seconds") + order("Value") + "\n";
Time time2= new Time();
time2.setToNow();
String seconds2 = time2.hour + ":" + (time2.minute < 10 ? "0"+time2.minute : time2.minute) + ":"
+ (time2.second < 10 ? "0"+time2.second : time2.second);
// creating the string to be written to file
String line2 = order(seconds2 + "") + order("" + msg.arg1)
+ "\n";
// write the string to file
writeToFileRawData(line2);
break;
Passing file name to next activity via intent:
Intent openActivity = new Intent(
"com.example.brianapp.mathsgameresults");
//sending session results + 4 text file names to new activity
openActivity.putExtra("fileNameRaw", fileNameRaw);
startActivity(openActivity);