FileNotFoundException while uploading a file from the SD card to a server - android

I got a FileNotFoundException error.
Code:
File getpath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
String dir= getpath.getAbsolutePath();
Log.e("filename of dir",dir);
//"/storage/emulated/0/Movies/"
try {
FileInputStream fstrm = new FileInputStream(dir+filename);
VideoFileUploadNew hfu = new VideoFileUploadNew( ServerURL.VIDEO_UPLOAD, filename);
upflag = hfu.Send_Now(fstrm);
Log.e("filename of v up",filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public class VideoFileUploadNew implements Runnable {
URL connectURL;
String responseString;
String Title;
String fileName;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public VideoFileUploadNew(String urlString, String file){
try{
connectURL = new URL(urlString);
fileName = file;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public Boolean Send_Now(FileInputStream fStream){
fileInputStream = fStream;
return Sending();
}
Boolean Sending(){
System.out.println("file Name is :"+fileName);
String iFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("Content-Disposition: form-data; name=\"vfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize =9024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int 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);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
if(String.valueOf(conn.getResponseCode()).equals("200"))
{
return true;
}else{
return false;
}
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
return false;
}
#Override
public void run() {
}
}

Your question is still pretty vague, but one of the reasons this happens is- when you're fetching the relative URI of the File, but need the Absolute URI for the upload.
You can check out different FileUtil classes like this https://github.com/z0rawarr/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/utils/FileUtils.java
Get the absolute path from the URI and use that to upload.
Also, do not forget to use the Debugger, and apply a breakpoint on uploadFile() to debug the URIs.

Related

Displaying upload progress in progress dialog

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.

File name not displayed properly

I want to upload an image to web server.For that i have written code,but when ever i upload the file to web server instead of file name i am getting the image path.
COde
protected String sendFile(final Context context, final String url, final String params, String fileName, final File f) {
DataOutputStream dos = null;
int bytesRead = 0, bytesAvailable = 0, bufferSize;
int maxBufferSize = 1024;
byte[] buffer;
String serverResponseMessage = null;
String uploaded_file = fileName;
URL url1 = null;
try {
FileInputStream fileInputStream = new FileInputStream(f);
url1 = new URL(url + "?" + params);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
fileName = String.valueOf(f);
//connection.setRequestProperty ("uploaded_file", "sample");
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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);
dos.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
StringBuffer b;
int ch;
InputStream is;
is = connection.getInputStream();
// retrieve the response from server
b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String response = b.toString();
Log.e("Response", "" + response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e("Error message", "" + e);
}
return serverResponseMessage;
}
protected File saveFile(Context context, int value, String name) {
File directory = new File(Environment.getExternalStorageDirectory() + "/pocketDocs/Camera/Gallery/Others");
if (!directory.exists()) {
directory.mkdirs();
}
if (value == 0) {
f = new File(Environment.getExternalStorageDirectory() + "/pocketDocs/Gallery", name);
try {
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return f;
}
}
When i use
fileName = String.valueOf(f);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
at server side i am getting the file name as the path of image.
And when i don't use
fileName = String.valueOf(f);
i am gettin the proper file name but i am not getting the extension of the image.
Now how can i solve this problem because the peoblem is in this line
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
You were using String.valueOf() in a file to get its name, it was returning an empty String, so it was not working.
Instead, you have to get the file name using file.getName().

Out of Memory Issue when encode into base64 video file

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.

Save and upload more than one image

I'm trying to upload more than one image taken from the camera. I call the camera via Intent:
public void TakePicture(int actionCode)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
photo[0] = createTemporaryFile("spot", ".jpg");
}
catch(Exception e)
{
Log.v("ERROR SD!!", "Can't create file to take picture!");
Toast.makeText(this, "Please check SD card! Image shot is impossible!", 10000);
}
fileUri = Uri.fromFile(photo[0]);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
And then I upload it to a PHP server:
public void UploadImg()
{
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
// String exsistingFileName = "/sdcard/prueba.png"; --> Used for local files!!
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://myUrl.com/uploadimg.php";
try
{
FileInputStream fileInputStream = new FileInputStream(photo[0].toString());
// Open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + photo[0] +"\"" + 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
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); }
catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); }
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
System.out.println("Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) { Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); }
}
I save 3 different images: photo[0], photo[1] and photo[2]. The problem is that when I take, for example, two pictures, it only uploads one of them and with size = 0.
In the code of the UploadImg() I show only the photo[0], but in the 'real' code I use a for loop after the first try so that it upload all of the images taken.
Any idea of what am I doing wrong?
Thank you very much in advance!
I've already solved my problem! I did the following: Instead of saving the photo File, I save the it in a String with the location of the image.
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
for (int u = 0; u <= 2; u++)
{
if (savedImgs[u].equals(""))
{
// Saving important info to be used later
imgs = u + 1;
savedImgs[u] = photo.toString();
break;
}
} ...
And then, when uploading the images to the server, I make a for loop like this:
public void UploadImg()
{
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
// String exsistingFileName = "/sdcard/prueba.png"; --> Used for local files!!
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://myUrl.com/uploadimg.php";
for (int n = 0; n < imgs; n++)
{
try
{
FileInputStream fileInputStream = new FileInputStream(savedImgs[n]);
// Open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + savedImgs[n] +"\"" + 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
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); }
catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); }
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
System.out.println("Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) { Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); }
}
}

Working with web service?

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");
}
?>

Categories

Resources