Sending an image file from android application to a server - java

I have used this code snippet to write an AsyncTask class that sends an image to a server. Here is a part of code in doInBackground method that is responsible for sending the image and a few arguments:
String fileName = params[3];
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(fileName);
if (!sourceFile.isFile()) {
Log.e("debug", "Source File not exist: " + fileName);
} else {
try {
/////////////////////////////////////////////////////////////////////////////
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(params[0]);
// 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("pic", fileName);
dos = new DataOutputStream(conn.getOutputStream());
//here I add some additional data
addFormField(dos,"idapp", params[1]);
addFormField(dos,"idlesson", params[2]);
addFormField(dos,"ip", params[4]);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";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);
String byteArray = "";
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
byteArray += buffer.toString();
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)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("debug", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
BufferedInputStream in;
try {
in = new BufferedInputStream(conn.getInputStream());
} catch (IOException e) {
String err = (e.getMessage() == null) ? "IOException in creating BufferedInputStream" : e.getMessage();
Log.e("debug", err);
return err;
}
try {
resultToDisplay = IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
} catch (IOException e) {
Log.e("debug", e.getMessage());
}
Log.i("debug", "result: " + resultToDisplay);
//close the streams //
//////////////////////////////////////
fileInputStream.close();
dos.flush();
dos.close();
//////////////////////////////////////
} catch (MalformedURLException ex) {
Log.e("debug", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
Log.e("debug", "error: " + e.getMessage(), e);
}
} // End else block
return resultToDisplay;
And here is how do I invoke it:
CallAPI c = new CallAPI();
c.execute(CallAPI.uploadURL, getResources().getString(R.string.appID), currentLessonID+"", pathToTempFile, CallAPI.IP);
The problem is that according to the response from the server, it recieves no image at all. This is a part of code that is responsible for the answer that I currently recieve:
if(!isset($_FILES['pic'])) ex_fail("pic not set");
if($_FILES['pic']['error'] != 0) ex_fail("pic upload error ");
I get "pic not set" error. Though according to the logs, I actually write the image into DataOutputStream, I compared the bytes count - it is the same.
What could cause the problem?

Related

Android Uploading Video as Multipart to Server

I am developing android application where user will upload video to server. I am new to android development so I cannot grasp the concept of uploading video. The thing I know is that I need to create an intent to ask user to choose the video and then convert it to uri file. I'm planning on using asynctask with httpurlconnection. Can anyone help me what to do with asynctask?
I think this will help you
upload video
public static int upLoad2Server(String sourceFileUri) {
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;
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 = "";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to
the URL
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);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
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("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
} // end upLoad2Server

Uploading Audio to Soundcloud from android app

I am recording audio and trying to upload audio on soundcloud server.but its not working can someone please correct me where i am doing wrong.I have searched alot but nothing works for me.I am a beginer in java.I already wasted 1 day on solving this problem.
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
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 = "http://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(AudioSavePathInDevice) );
// 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);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+contributor_name+lineEnd);
// dos.writeBytes(lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
// dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + AudioSavePathInDevice + "\"" + lineEnd);
// dos.writeBytes(lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+sharing+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);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
//------------------ read the SERVER RESPONSE
// try {
// DataInputStream inStream = new DataInputStream ( conn.getInputStream() );
// String str;
// Log.e("Debug","Before while");
// while (( str = inStream.readLine()) != null)
// {
// Log.e("Debug","Server Response "+str);
// }
// inStream.close();
//
// }
try (InputStream is = conn.getInputStream()) {
BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// if(is == null) {
// Log.e("Debug","Reponse null ");
// }
// if(lines == null) {
// Log.e("Debug","Reponse null ");
// }
// int count = 0;
while (true) {
Log.e("Debug","Server Response ");
String line = lines.readLine();
if (line == null) {
Log.e("Debug","Server Break");
break;
}
}
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
and calling Asynctask like below on onClicklistener.
new AsyncTaskRunner().execute();

Which content-type to use when Uploading sqlite .db file to a server?

I want to upload a .db (SQLite) file from my android app to a server and I'm wondering if I can use "multipart/form-data" as the content-type. Is there any specific type for .db file as for pdf files which is "application/pdf" ?
I actually got it working with just the "multipart/form-data" as the content type. When I tried the 'application/x-sqlite3', I had an error.
Here is the code snippet I used to post the .db file to server, borrowed from this link:
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri; // the path to my .db file
HttpURLConnection connection = null;
DataOutputStream dataOutputStream = 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()) {
Log.e("uploadFile", "Source File not exist ");
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
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); //Triggers http POST method.
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//conn.setRequestProperty("Content-Type", "application/x-sqlite3; boundary=" + boundary);// when I tried this it didn't work, so you can delete this line
connection.setRequestProperty("uploadedfile", fileName);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=" + fileName + "" + lineEnd);
dataOutputStream.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) {
dataOutputStream.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...
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
String msg = "server respose code ";
Log.i(TAG, msg + serverResponseCode);
StringBuilder result = new StringBuilder();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
//JSONObject mResponseJSONObject = new JSONObject(String.valueOf(result)); //convert the respons in json
Log.i(TAG, msg + result);
}
//close the streams //
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e(TAG, "MalformedURLException Exception : check script url.");
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Upload file to server Exception : " + e.getMessage(), e);
}
return serverResponseCode;
} // End else block
} //[End uploadFileToServer method]
This is php script I used on the server side:
<?php
if(isset($_FILES)) {
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], "./data/".$_FILES["uploadedfile"]["name"]."_".time())) {
echo " file recieved successfully"
exit;
}
}
echo "Error";
?>

Upload file from android to ASP .net using http POST method

I need to upload my file android device to server using webservice. But unfortunately Im getting error while doing it.Please help me to clear this error.
Here is my java code:
public class HttpFileUpload implements Runnable {
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String iFileName = "ovicam_temp_vid.mp4";
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(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
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();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
ioe.printStackTrace();
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
LogCat:
java.io.FileNotFoundException: http:///****8*******8/*****
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:210)
at arun.com.test.HttpFileUpload.Sending(HttpFileUpload.java:118)
at arun.com.test.HttpFileUpload.Send_Now(HttpFileUpload.java:36)
the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = conn.getInputStream();
by
int status = conn.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
Taken from this answer

Android writing to file

I'm trying to write a file and upload it, however, the file does not seem to be written properly (as later on that I need to upload it, it crashes and says no file). I'm following the guidelines of Google's documentation. Here's my code:
String fileLocation = "Hello";
String TESTSTRING = new String("Hello Android");
FileOutputStream fOut = openFileOutput(fileLocation, MODE_WORLD_READABLE);
fOut.write(TESTSTRING.getBytes());
fOut.close();
That's how I'm trying to upload:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = fileLocation;
String Tag = "UPLOADER";
HttpURLConnection conn = null;
String urlServer = "http://..."; //my server
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
// ------------------ CLIENT REQUEST
Log.e(Tag, "Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));
// open a URL connection to the Servlet
URL url = new URL(urlServer);
// 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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos
.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ fileLocation + "" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.e("Dialoge Box", "Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
Here's the PHP code on the server:
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
Instead of using
FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));
use
FileInputStream fileInputStream = openFileInput(fileLocation);
try something like this:
fileLocation = context.getFilesDir() + "Hello";
I'm not sure that you can/should write files to the root directory like that.
Please, first Write a String like this, than you send the file to server. It will help some one.
String resp = "Hello Andrid!!!";
File file= new File("/sdcard/hello.xml");
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(resp.getBytes());
fos.flush();
fos.close();
Log.d("File Write is success","fine");
} catch (Exception e) {
Log.d("Error in File write: ", ""+e.getMessage());
} finally {
if (fos != null) {
fos = null;
}
}

Categories