How to send file through http post method without additional info? - android

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);

Related

Posting image to apache server by multipart-data requests via urlConnection Android app,server response 0 files found.

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;
}

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.

Android upload removes bytes

I'm trying to upload a video from my android phone (Samsung Galaxy s2) with version 4.1.2.
I have configured an apache server which hosts the uploaded video. My problem is the following : everytime I upload a video from my phone, I have a corrupted file. The file on the server has a few bytes less than the phone's file. It does not come from the server as I've made some tests using an html form and everything went well. So I guess, it's coming from my code but I just can't figure where. Can somebody help me please, I've spent days on it.
This is my code :
#Override
public boolean uploadFile() {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = mMedia.getLocalPath();
String urlServer = UploadConf.UPLOAD_SERVER;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize, totalBytesRead;
byte[] buffer;
int maxBufferSize = UploadConf.MAX_BUFFER_SIZE;
try {
File file = new File(pathToOurFile);
FileInputStream fileInputStream = new FileInputStream(file);
Log.i(LOG_TAG, "MediaUploader upload" + file.getName() + " => " + file.getPath());
Map<String, String> params = new HashMap<String, String>();
params.put("mediaTitle", file.getName());
URL url = new URL(urlServer + getFormattedParams(params));
Log.i(LOG_TAG, "URL => " + urlServer + getFormattedParams(params));
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(UploadConf.CHUNK_SIZE);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"mediaFile\"" + lineEnd + lineEnd + file.getName() + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"video_file\";filename=\"" + file.getName());
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesRead = bytesRead;
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i(LOG_TAG, "Progress " + totalBytesRead + " Read ");
totalBytesRead += bytesRead;
//outputStream.flush();
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d(LOG_TAG,"Server Response Code " + serverResponseCode);
Log.d(LOG_TAG,"Server Response Message " + serverResponseMessage);
Log.d(LOG_TAG,"Server Response " + response.toString());
String result = response.toString();
if (result == null || result.equals("")) {
broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
}
JSONObject json = null;
try {
json = new JSONObject(result);
}
catch (JSONException e) {
Log.e(LOG_TAG, "Impossible to parse Json String");
broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
return false;
}
JSONObject jsonResult = json.getJSONObject(Constants.JSON_RESULT_TAG);
if (jsonResult == null) {
Log.e(LOG_TAG, "Json result is null ");
broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
return false;
}
JSONArray errors;
if (jsonResult.has(Constants.JSON_ERRORS_TAG)) {
if ((errors = jsonResult.getJSONArray(Constants.JSON_ERRORS_TAG)) != null) {
String notification = "";
for (int i = 0; i < errors.length(); i++) {
JSONObject o = errors.getJSONObject(i);
notification += o.getString(Constants.JSON_ERROR_TAG);
}
broadcastIntent(notification, PRIORITY.ERROR, null, null);
return false;
}
}
mMedia.setSyncState(SyncState.SYNCED.ordinal());
mMediaManager.updateMedia(mMedia);
broadcastIntent(mContext.getString(R.string.upload_succeedeed_notification), PRIORITY.INFO, fileInputStream, outputStream);
return true;
} catch (UnknownHostException ex) {
broadcastIntent(mContext.getString(R.string.upload_hostname_error_notification), PRIORITY.ERROR, null, null);
Log.d(LOG_TAG, ex.getStackTrace().toString());
} catch (Exception ex) {
broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, null, null);
Log.d(LOG_TAG,"Upload failed");
ex.printStackTrace();
}
return false;
}

Opening DataInputStream running very slow

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.

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