I am uploading a file to a server and depending on the processing on the file I get a different reply from the server. Everything is working, however getting the reply from the server is very slow. I checked in the debugger and the following line of code is taking 6 seconds to run.
inStream = new DataInputStream( connection.getInputStream() );
I have tested the same files and code over a web browser and its perfect, taking about 1 or 2 seconds to display the reply. Here is my full code, I think its ok, but maybe there is something here that is not done properly. Is there a better way of doing this? Or is a new DataInputStream always going to be so slow?
private String loadImageFromNetwork(String myfile) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String make = "";
String model = "";
String disp = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://xxxxxxxxxxxxxx/upload.php";
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + myfile)));
try {
FileInputStream fileInputStream = new FileInputStream(new File(myfile));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs
connection.setDoInput(true);
// Allow Outputs
connection.setDoOutput(true);
// Don't use a cached copy.
connection.setUseCaches(false);
// Use a post method.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + myfile +"\"" + lineEnd);
outStream.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) {
outStream.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...
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
outStream.flush();
outStream.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
return disp;
}
You should move the code to read the response from the server to a new thread. Ex:
private class ReadResponse implements Runnable {
public void run() {
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
//return disp;
//here you need to show your display on UI thread
}
}
}
and start the reading thread before uploading the file.
Related
Since the Android developers recommend to use the HttpURLConnection
class, I was wondering if anyone can provide me with a good example on
how to send a bitmap "file" (actually an in-memory stream) via POST to
an Apache HTTP server. I'm not interested in cookies or authentication
or anything complicated, but I just want to have a reliable and logic
implementation. All the examples that I've seen around here look more
like "let's try this and maybe it works".
posting image to apache server multipart-data request
via urlConnection
opening image as a fileinputStream
then posting image to server
server replies 0 files found
there is my example function
public String editProfile1 (){
String serverResponseJsonStr = null;
File temp_file = null;
InputStream fileInputStream = null;
ContextWrapper cw = new ContextWrapper(cntxt);
// path to /data/data/yourapp/app_data/imageDir
File path = cw.getDir("imageDir", Context.MODE_PRIVATE);
//File path1 = cw.getFileStreamPath("user photos");
Log.i("check file path",cw.getFileStreamPath("user photos").toString());
//cheking if profile picture changed send it to server
if (isProfileImageChanged){
temp_file=new File(path+PROFILE_IMAGE_FOLDER, "profile");
if (!temp_file.isFile()) {
Log.e("%%%uploadIAmge", "Source File Does not exist");
}else {
Log.e("%%%uploadIAmge path", temp_file.getPath());
}
try {
fileInputStream = new FileInputStream(temp_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String lineEnd = "\r\n";
String twoHyphens = "---------------------------";
String boundary = "acebdf13572468";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
HttpURLConnection conn = null;
DataOutputStream dos = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedOutputStream outputStreams =null;
int maxBufferSize = 1*1024*1024;
// open a URL connection
try {
int chiko = fileInputStream.available();
Log.i("$$$$$$$$$$$$",String.valueOf(chiko));
} catch (IOException e) {
e.printStackTrace();
}
try {
//constants
//trustEveryone();
URL url = new URL(NetworkURLS.SetUserProfilePicture);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy
conn.setUseCaches(false);
// Use a post method.
//make some HTTP header nicety
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + twoHyphens + boundary);
conn.setRequestProperty("FileName", temp_file.getName());
dos = new DataOutputStream( conn.getOutputStream() )
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"UserProfilePicture\";FileName=\"" + temp_file.getName()+"\"" + lineEnd);
dos.writeBytes("Content-Type:\"image/jpeg\"" +lineEnd);
// dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
if (fileInputStream != null){
Log.i("###fileInputStream","is note null");
// 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 + lineEnd);
// close streams
fileInputStream.close();
}else {
Log.i("###fileInputStream","is null");
}
dos.flush();
dos.close();
// Log.i("$$ respones :", String.valueOf(conn.getResponseCode()));
//clean up
Integer result = conn.getResponseCode();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
//do somehting with response
inputStream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer1 = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer1.append(line + "\n");
}
if (buffer1.length() == 0) {
// Stream was empty. No point in parsing.
Log.i("$$ getrespponse :", "response was empty");
return "";
}
reader.close();
serverResponseJsonStr = buffer1.toString();
Log.i("$$ getrespponse :", serverResponseJsonStr);
} else {
// Server returned HTTP error code.
Log.i("$$ respones :", String.valueOf(result));
}
//String contentAsString = readIt(inputStream,len);
} catch (IOException e) {
e.printStackTrace();
} finally {
//clean up
try {
if (outputStreams!= null) outputStreams.close();
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return serverResponseJsonStr;
}
I'm uploading a file and want to display a progress dialog to see the upload progress. I already included a horizontal dialog which works incorrectly, because it goes to 100% in 1 second and then it waits (because it's still uploading).
I used the following function for uploading:
private void doFileUpload(String selectedPath){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "https://xxxxxxxxxx.com";
try
{
//------------------ CLIENT REQUEST
File f = new File(selectedPath);
FileInputStream fileInputStream = new FileInputStream(f);
//calculate size of file
wholeFilesize = f.length(); //returns the length in Bytes
// open a URL connection to the Servlet
URL url = new URL(urlString);
// 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=\"upfile\";filename=\"" + selectedPath + "\"" + 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)
{
totalReadFilesize+=bytesRead;
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
int progress = (int)((totalReadFilesize*100)/(wholeFilesize));
//Log.i("Progress: ", (int)((totalReadFilesize*100)/(wholeFilesize))+"");
dialog.setProgress(progress);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
//publishProgress(100);
Log.i("Size: ", wholeFilesize+"");
Log.i("Bytes read: ", totalReadFilesize+"");
// 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");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
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);
JSONObject jsonObj = new JSONObject(str);
//String status=(String) jsonObj.get("status");
Log.i("TEST", (String) jsonObj.get("message"));
uploadResultMessage = (String) jsonObj.get("message");
Log.i("TEST", uploadResultMessage);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
}
}
Does someone know, how should I modify the code to see the real progress of the file, which is being uploaded? I find it strange, because I'm doing the same as the user in his doInBackground() in this thread.
I am trying to upload the video file into server with convert into base64. But I am getting out of memory exception even size is 2 mb also. How to resolve this issue. Please help me to over out, much appreciate your help.
Here what I am doing
byte [] ba = convertByteArray(videoUri);
String baseimage=Base64.encodeToString(ba, Base64.NO_WRAP);
public byte[] convertByteArray(Uri videoUri){
InputStream iStream=null;
byte[] inputData=null;
try {
iStream = getContentResolver().openInputStream(videoUri);
inputData = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return inputData;
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Code :
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// 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="uploadedfile";filename="" + selectedPath + """ + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
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);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Go through the following Sample for more reference :
http://coderzheaven.com/2011/08/uploading-audio-video-or-image-files-from-android-to-server/
For uploading video to server see doFileUpload() method from the above url.
I am sending a file from sd card by using the following code.
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/111";
File f = new File(existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.178.1.7/Geo/Prodect(filename)";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(f);
// open a URL connection to the Servlet
URL url = new URL(urlString);
// 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=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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)
Log.v("info",".size."+bytesRead);
for(int n1=0;n1<bytesRead;n1++)
{
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);
// close streams
Log.v("info","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.v("info", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.v("info", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.v("info","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex)
{
Log.v("info", "error: " + ioex.getMessage(), ioex);
}
It works fine but,the file contains 20 lines it saved in the sever with 22 lines.
My actual file looks like as follows.
android app info
app name
app time
when i will send the flle to server from sd card the file look like as follows
1)**mnt/sdcard/111**
android app info
app name
app time
2)**
1 and 2 lines are added.
How i can send a file without those two lines .
If any one know the solution please help me .
Thanks in advance..
public static StringBuffer post(String url,InputStream in) throws IOException {
InputStream bufferInputStream = null;
InputStreamReader responseInputStream = null;
HttpURLConnection conn = null;
OutputStream requestOutputStream = null;
StringBuffer responseString = new StringBuffer();
int bufferSize = 8192;
byte[] byteBuffer = new byte[bufferSize];
int postDataSize = 0;
try {
if (in != null) {
bufferInputStream = new BufferedInputStream(in);
}
if (bufferInputStream != null) {
postDataSize = bufferInputStream.available();
}
//send request
conn = getConnecttion(url);
if (postDataSize > 0) {
requestOutputStream = conn.getOutputStream();
int position = 0;
while ((position = bufferInputStream.read(byteBuffer)) > -1) {
requestOutputStream.write(byteBuffer, 0, position);
}
requestOutputStream.flush();
requestOutputStream.close();
requestOutputStream = null;
byteBuffer = null;
}
// get response
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[bufferSize];
int _postion = 0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
responseString.append(charBuffer,0,_postion);
}
responseInputStream.close();
responseInputStream = null;
charBuffer = null;
}else{
throw new IOException("Respsone code:"+responseCode);
}
} catch (Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} finally {
byteBuffer = null;
if (responseInputStream != null) {
responseInputStream.close();
responseInputStream = null;
}
if (conn != null) {
conn.disconnect();
conn = null;
}
if (requestOutputStream != null) {
requestOutputStream.close();
requestOutputStream = null;
}
if (bufferInputStream != null) {
bufferInputStream.close();
bufferInputStream = null;
}
}
return responseString;
}
Please reference to above simple code,
send file like this:post("http://youurl.com",new FileInputStream(" you file path"))
Try commenting the following
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(lineEnd);
I want to copy all the video files on my server & save it in the web contents folder of a web service , so that it can be visible to all later on !
How should i proceeed ?
Basically you need two sides. The first one is on Android. You have to send (Do it in an ASyncTask e.x.) the data to your webservice. Here I made a little method for you, which sends a file and some additional POST values to an URL:
private boolean handleFile(String filePath, String mimeType) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://your.domain.com/webservice.php";
try {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filePath));
} catch(FileNotFoundException e) { }
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
// Some POST values
outStream.writeBytes(addParam("additional_param", "some value");
outStream.writeBytes(addParam("additional_param 2", "some other value");
// The file with the name "uploadedfile"
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filePath +"\"" + lineEnd + "Content-Type: " + mimeType + lineEnd + "Content-Transfer-Encoding: binary" + lineEnd);
outStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
outStream.flush();
outStream.close();
} catch (MalformedURLException e) {
Log.e("APP", "MalformedURLException while sending\n" + e.getMessage());
} catch (IOException e) {
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
// This part checks the response of the server. If its "UPLOAD OK" the method returns true
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null) {
if(str=="UPLOAD OK") {
return true;
} else {
return false;
}
}
inStream.close();
} catch (IOException e){
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
return false;
}
Now, we have got the other side: http://your.domain.com/webservice.php
Your server. It needs some logic, for example in PHP, to handle the sent POST request.
Something like this would work:
<?php
$target_path = "videos/";
$target_path = $target_path.'somename.3gp';
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
exit("UPLOAD OK");
} else {
exit("UPLOAD NOT OK");
}
?>