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);
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 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();
}
}
I make this HTTP POST request in my Android application:
private final String delimiter = "--";
private final String boundary = "SwA"
+ Long.toString(System.currentTimeMillis()) + "SwA";
private final String charset = "UTF-8";
private final String lineSpace = "\r\n";
private final String domain = (domain);
private HttpURLConnection configureConnectionForMultipart(String url)
throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) (new URL(url))
.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
+ boundary);
return con;
}
private void addFormPart(String paramName, String value, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"" + lineSpace);
os.writeBytes("Content-Type: text/plain; charset=" + charset
+ lineSpace);
os.writeBytes(lineSpace + value + lineSpace);
os.flush();
}
private void addFilePart(String paramName, File data, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"; filename=\"" + data.getAbsolutePath() + "\"" + lineSpace);
os.writeBytes("Content-Type: application/octet \r\n");
os.writeBytes("Content-Transfer-Encoding: binary" + lineSpace);
// os.writeBytes(lineSpace);
os.flush();
FileInputStream fis = new FileInputStream(data);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.writeBytes(lineSpace);
os.flush();
fis.close();
}
private void finishMultipart(DataOutputStream os) throws IOException {
// os.writeBytes(lineSpace);
os.flush();
os.writeBytes(delimiter + boundary + delimiter + lineSpace);
os.close();
}
private class ObjectUploadRunnable implements Runnable {
private final String _filePath;
private final String _url = domain + "upload.php";
public ObjectUploadRunnable(String filePath) {
_filePath = filePath;
}
#Override
public void run() {
try {
HttpURLConnection con = configureConnectionForMultipart(_url);
con.connect();
DataOutputStream os = new DataOutputStream(
con.getOutputStream());
File data = new File(_filePath);
addFilePart("data", data, os);
finishMultipart(os);
String response = getResponse(con);
Log.i("BoxUpload", response);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I catch it on my server with the script upload.php:
...
$dir = "/uploads/";
$target_path = $dir.basename($_FILES['data']['name']);
if (move_uploaded_file($_FILES['data']['tmp_name'], $target_path)) {
echo "file uploaded";
} else {
echo print_r(error_get_last());
}
Everything seems to succeed, in that a file with the correct size gets uploaded to my server, in the desired directory. However, when I try to open the file, it seems to be damaged or corrupted in some way because it won't open in any application that I try. I'm uploading images=jpeg, videos=mp4, audio=mp4. These files are all working on the client before upload. Am I missing something to encode the files correctly in the POST request? I've never done file uploads before, so I'd appreciate some advice...
EDIT
In case this is relevant, I've noticed that the files which I've uploaded have grown by ~100kb. Maybe something's getting added to my binary data which is corrupting the file?
Figured out the problem here. That extra line that I commented out in addFilePart was actually necessary. I guess there needs to be two lines between the header info and the binary data in that part of the request. To be clear, it should look like:
private void addFilePart(String paramName, File data, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"; filename=\"" + data.getAbsolutePath() + "\"" + lineSpace);
os.writeBytes("Content-Type: application/octet \r\n");
os.writeBytes("Content-Transfer-Encoding: binary" + lineSpace);
os.writeBytes(lineSpace);
os.flush();
FileInputStream fis = new FileInputStream(data);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.writeBytes(lineSpace);
os.flush();
fis.close();
}
Everything works great now!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I have an android app that upload a file to server , it's work without any problem in local host, but not working on the server, I have checked the path and it correct,
the log cat error: Not Found : 404
if i copy the url in paste it in the browser it's work
i have another php file in the same address (up3.php) and that one working without any problem but in that one I use Json to send text, not uploading file
I have searched for solution but didn't find anything,
this is my codes:
String upLoadServerUri = "http://live.mysite.com/up-file.php";
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();
runOnUiThread(new Runnable() {
public void run() {
}
});
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("Accept-Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data ; charset=utf-8 ;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"post_id\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(post_id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"username\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(username);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data ; name=\"txt\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeUTF(up_txt);
dos.writeBytes(lineEnd);
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() {
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
Log cat:
10-16 06:08:53.632: W/IInputConnectionWrapper(2571): showStatusIcon on inactive InputConnection
10-16 06:08:58.541: D/dalvikvm(2571): GC_CONCURRENT freed 169K, 3% free 9758K/10055K, paused 15ms+1ms, total 18ms
10-16 06:08:58.551: D/dalvikvm(2571): GC_FOR_ALLOC freed 608K, 10% free 9150K/10055K, paused 2ms, total 2ms
10-16 06:08:58.551: I/dalvikvm-heap(2571): Grow heap (frag case) to 10.340MB for 1440012-byte allocation
10-16 06:08:58.571: D/dalvikvm(2571): GC_CONCURRENT freed 0K, 8% free 10557K/11463K, paused 12ms+1ms, total 15ms
10-16 06:09:03.742: I/Choreographer(2571): Skipped 30 frames! The application may be doing too much work on its main thread.
10-16 06:09:11.862: I/uploadFile(2571): HTTP Response is : Not Found: 404
http://live.mysite.com/up-file.php throws a 404 error, that's why it does not work
$ wget http://live.mysite.com/up-file.php
--2014-10-17 17:00:40-- http://live.mysite.com/up-file.php
Résolution de live.mysite.com (live.mysite.com)... 64.136.20.37
Connexion vers live.mysite.com (live.mysite.com)|64.136.20.37|:80...connecté.
requête HTTP transmise, en attente de la réponse...404 Not Found
2014-10-17 17:00:41 ERREUR 404: Not Found.
In a browser, it shows a fancy 404 page, but still 404
404 Error - File Not Found
The page or file you are looking for is not here.
I found the solution , I don't know why but httprequest doesn't find the sub domain ,
instead of http://live.mysite.com/up.php it must be http://www.live.mysite.com/up.php , if any one know why this happen tell me plz