Android upload removes bytes - android

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

Related

Multiple image upload in single multipart request with String Data Android

I'm Working on used goods sell Android application where I want to upload multiple images of goods on server.User can upload maximum 4 images of and at least he has to upload one image of goods.The number of goods images may vary between 1 to 4,it depends on user what number of images he wants to upload.
Now my question is that how can I upload multiple images with String data to server in a single multipart request
Condition
the number of images upload is vary between 1 to 4 images.
Below is my codes for uploading single image to server with string data.
try {
if (selectedImage.equals(null)) {
Toast.makeText(MainActivity.this, "Choose Image First", Toast.LENGTH_LONG).show();
} else {
tvLoad.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "34242");
params.put("user_city", "Delhi");
params.put("category", "vehicle");
params.put("subcategory", "car");
params.put("brand", "honda");
params.put("model", "2019");
params.put("fuel", "petrol");
params.put("conditn", "good");
params.put("title", "title");
params.put("description", "description");
params.put("year", "2018");
params.put("kmdriven", "90000");
params.put("price", "100000");
Log.e("abc", " =============" + link);
try {
multipartRequest(link, params, selectedImage + "", "image", "image/jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "Choose Image First", Toast.LENGTH_LONG).show();
}
public void multipartRequest(String urlTo, Map<String, String>
parmas, String filepath, String filefield, String fileMimeType) throws
Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" +
Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
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=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (200 != connection.getResponseCode()) {
throw new Exception("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
JSONObject jsonObject = new JSONObject(result);
if(jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this, "Service Added", Toast.LENGTH_LONG).show();
}else{
}
tvLoad.setText("Successfully loaded");
Log.e("abc", " ========= result === " + result) ;
try {
JSONObject jsonObject1 = new JSONObject(result);
String link = jsonObject1.getString("link");
tvLink.setText(link);
}catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I recommend my lightweight library with I have described in this answer https://stackoverflow.com/a/53253933/8849079

How to send File and String data using HttpURLConnection in android

I am using HttpURLConnection to upload a file to the server but i could not figure out how can i add other parameters to send String data along with file.
This is the code i am using to upload the file.
public String sendFileToServer(String filename, String targetUrl) {
String response = "error";
Log.e("Image filename", filename);
Log.e("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// 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);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.i("Connstr", connstr);
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Image length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
String CDate = null;
Date serverTime = new Date(connection.getDate());
try {
CDate = df.format(serverTime);
} catch (Exception e) {
e.printStackTrace();
Log.e("Date Exception", e.getMessage() + " Parse Exception");
}
Log.i("Server Response Time", CDate + "");
filename = CDate
+ filename.substring(filename.lastIndexOf("."),
filename.length());
Log.i("File Name in Server : ", filename);
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
I have used Volley previously but it fails to upload when file is large, I have to upload Video files up to 20 MB, so if you have any better solution please let me know.
I am using this code in Service so even if user close the app the uploading should continue.
The following code should work:
outputStream = new DataOutputStream(connection.getOutputStream());
// To send string data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + stringName + "\""+lineEnd);
outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(stringValue + lineEnd);
outputStream.flush();
// To send file data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
For more details: link

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

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

Upload large file in Android without outofmemory error

My upload code as below:
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(ActionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Accept", "text/*");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end);
ds.write(SavePath.getBytes("UTF-8"));
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\"");
ds.write(FileName.getBytes("UTF-8"));
ds.writeBytes("\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(uploadFilepath+""+FileName);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
int pro = 0;
while((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while((ch = is.read()) != -1) {
b.append((char)ch);
}
ds.close();
}
catch(Exception e) {
e.printStackTrace();
}
While smaller than 16 mb, it upload success.
But while it more than 16 mb, the "OutOfMemory" error show.
How to avoid the outofmemory error?
Did you try using
con.setChunkedStreamingMode(1024);
This will help you to chunk your data into specific size, so that you need not keep your entire file in the memory.
UPDATE:
Try using the below method. I use this method to upload a 80 mb file without Exception.
public String sendFileToServer(String filename, String targetUrl) {
String response = "error";
Log.e("Image filename", filename);
Log.e("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// 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);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.i("Connstr", connstr);
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Image length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
String CDate = null;
Date serverTime = new Date(connection.getDate());
try {
CDate = df.format(serverTime);
} catch (Exception e) {
e.printStackTrace();
Log.e("Date Exception", e.getMessage() + " Parse Exception");
}
Log.i("Server Response Time", CDate + "");
filename = CDate
+ filename.substring(filename.lastIndexOf("."),
filename.length());
Log.i("File Name in Server : ", filename);
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
if Server accept chunked mode, you can use
((HttpURLConnection) con).setChunkedStreamingMode(chunkLength)
otherwise you can use
((HttpURLConnection) con).setChunkedStreamingMode(0);
or
/* compute first your request content length
contentLength = formBodyLength + yourFileSize
*/
con.setRequestProperty("Content-Length", String.valueOf(contentLength));
((HttpURLConnection) con).setFixedLengthStreamingMode(contentLength);
finally... send what you want
bitmap=Bitmap.createScaledBitmap(bitmap, 100, 100, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); //compress to format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
Best Way I tried it was successful for me!!!

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