How to upload video more faster in android - android

I am trying video based application. I am using below method to upload video file, when I am sending large size of video file it's getting more time to upload. So I need to compress the data and also video file size should be less than 30 MB.I am bad in English forgive me. Can anyone give me the solution for my question?
private void doFileUpload(){
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://mywebsite.com/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);
}
}

You can try HttpClient jar download the latest HttpClient jar, add it to your project, and upload the video using the following method:
private void uploadVideo(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )

Related

Error in uploading audio file to server in Android

Please tell me why am I getting this error?
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable = 0, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://thinksl.com/taughtable/audiopost.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(path) );
// 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);
conn.setRequestProperty("userfile",path);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" +path+ "\"" + lineEnd);
Log.e("Debug", "Filename: " +path);
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);
}
Log cat
Server Response
{"result":0,"post":[],"files":[],"filename":null,"message":"There was
an error uploading the file, please try again!"}
Use following method to upload audio file to server.
private String uploadAudio(final String filePath) {
String extension = filePath.substring(filePath.lastIndexOf("."));
Log.e(extension);
String response = null;
String final_upload_filename = "sample_audio"+ extension;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL("http://thinksl.com/taughtable/audiopost.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(1024);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", final_upload_filename);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
fileInputStream.close();
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytessRead;
byte[] bytes = new byte[1024];
while ((bytessRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytessRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
response = new String(bytesReceived);
Log.e("Server Response" + response);
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
return response;
}
I hope it helps!
Why don't you try like this,
try {
HttpClient httpClient = new DefaultHttpClient();
String url = "http://thinksl.com/taughtable/audiopost.php";
HttpPost httppost = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", new FileBody(new File(path)));
reqEntity.addPart("filename", final_upload_filename);
httppost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
Log.e(TAG, "Response: " + s);
status = "" + s;
} catch (Exception e) {
e.printStackTrace();
}

How to upload Image on Android?

I havve to upload image from my SD card to PHP server. I have read a lot of articles and topics but I have some problems...
First I have use that code:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
//DataInputStream inputStream = null;
String urlServer = hostName+"Upload";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String serverResponseMessage;
//int serverResponseCode;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
showLog("uploading file: " + file);
FileInputStream fileInputStream = new FileInputStream(new File(pictureFileDir+"/"+file) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
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=\"uploaded_file\";filename=\"" + file +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
//serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
showLog("server response: " + serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
but server response 200/OK and no file was on destination server...
After i have read about Multipart:
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient mHttpClient = new DefaultHttpClient(params);
File image = new File(pictureFileDir + "/" + filename);
HttpPost httppost = new HttpPost(hostName+"Upload");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
e.printStackTrace();
}
but then a i have such LOG in LogCat and nothing else...
06-04 06:50:52.277: D/dalvikvm(1584): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
06-04 06:50:52.277: W/dalvikvm(1584): VFY: unable to resolve static field 6688 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
06-04 06:50:52.277: D/dalvikvm(1584): VFY: replacing opcode 0x62 at 0x001b
ServerSide Script:
$target_path = "uploads";
$target_path = $target_path . basename( $_FILES['Image']);
if(move_uploaded_file($_FILES['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
why? What is the simplest way to upload image?
You'll need the httpmime and httpcore libraries for this code.
Then, do this:
try {
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(YOUR_ABSOLUTE_PATH_STRING);
if (!file.exists())
return null;
mBuilder.addPart("mFile", new FileBody(file));
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(YOUR_SERVER_URL);
httpPost.setEntity(mBuilder.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//Reading the response:
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
httpEntity.consumeContent();
//Do something with the string returned: sb.toString()
} catch (Exception e) {}
PHP Code
$fileName = uniqid() . ".png";
if (move_uploaded_file($_FILES["mFile"]["tmp_name"], "uploads/" . $fileName))
return $fileName;
return "";
This code works for me, so if it doesn't work for you - check the image path you're sending, try a different image etc.
Try this,it is also using multipart, it worked for me.
try {
String url = "<destination-path>";
String fileName = ""; //file to be uploaded
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent = new FiSystem.out.println("hello");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
OK finally everything work :) I have used that code:
try {
showLog("uploading file: " + file);
File image = new File(pictureFileDir + "/" + file);
FileInputStream fileInputStream = new FileInputStream(image);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
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=\"uploadedfile\";filename=\"" + pictureFileDir + "/" + file + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
//serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
showLog("server response: " + serverResponseMessage);
image.delete();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
and PHP script:
$target_path = "uploads/";
$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!";
}
Thanks everyone :)

Uploading Image to Server - Android

I have got the Rest Api's link and the sample code for uploading the image in C sharp but how to upload image to server from android the same thing using java
Here's that sample code
http://xx.xx.xxx.xx/restservice/photos
Sample code for uploading file:
string requestUrl = string.Format("{0}/UploadPhoto/{1}", url,filnm);
//file name should be uniqque
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "text/plain";
byte[] fileToSend = FileUpload1.FileBytes; //File bytes
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
how you will you do it with the android
EDITED:
With the help of your answer I have written the code over here but I am getting 404 connection response and the ERROR ERROR
public class ImageUploadToServer extends Activity {
TextView messageText;
Button uploadButton;
String upLoadServerUri = null;
String urlLink = "http://xx.xx.xxx.xx/restservice/photos/";
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/myimg.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
uploadData();
}
public void uploadData ()
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
// FileInputStream fileInputStream = new FileInputStream(new File(path));
File sourceFile = new File(path);
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(urlLink);
connection = (HttpURLConnection) url.openConnection();
Log.d("Connection:", "Connection" + connection.getResponseCode());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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=\"uploadedfile\";filename=\""
+ path + "\"" + 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);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream responseStream = new BufferedInputStream(connection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", "Server Respone" + response);
responseStream.close();
connection.disconnect();
} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}
}
}
I am currently using this code to upload small videos to server (PHP server side).
Take not that the apache HttpClient is not supported anymore, so HttpURLConnection is the way to go.
try {
FileInputStream fileInputStream = new FileInputStream(new File(
path));
URL url = new URL(urlLink);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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=\"uploadedfile\";filename=\""
+ path + "\"" + 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);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream responseStream = new BufferedInputStream(connection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", response);
responseStream.close();
connection.disconnect();
} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}
}
here is the PHP that may help you for receiving the file on your server.
<?php
try {
// Checking for upload attack and rendering invalid.
if (
!isset($_FILES['uploadedfile']['error']) ||
is_array($_FILES['uploadedfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// checking for error value on upload
switch ($_FILES['uploadedfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// checking file size
if ($_FILES['uploadedfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// checking MIME type for mp4... change this to suit your needs
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['uploadedfile']['tmp_name']),
array(
'mp4' => 'video/mp4',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// Uniquely naming each uploaded for file
if (!move_uploaded_file(
$_FILES['uploadedfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['uploadedfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
// response code.
echo 'File is uploaded successfully!';
}
catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
try this....
public static JSONObject postFile(String url,String filePath,int id){
String result="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
File file = new File(filePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
StringBody stringBody= null;
JSONObject responseObject=null;
try {
stringBody = new StringBody(id+"");
mpEntity.addPart("file", cbFile);
mpEntity.addPart("id",stringBody);
httpPost.setEntity(mpEntity);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
result=resEntity.toString();
responseObject=new JSONObject(result);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseObject;
}

how to send file from sd card to http post?

i want to send file from our app to sever through http post method.
My code is looking like as fallows
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/TamTrack/TamTrackDetails.xml";
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.158.1.7/Geo/myfilename";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// 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);
}
return null;
It is working fine.but empty file is created in server.
If any one know the solution ,please help me .
Thanks in advance.
Try this code. It is using a class "SimpleMultipartEntity" using which you can easily send the file.
I'd prefer using Apache Http commons, it is part of android. I think this is a much simpler and cleaner approach. You need to do something like this:
AndroidHttpClient client = AndroidHttpClient.newInstance("useragent string");
URI uri = "something";
File file = new File("/tmp/data");
HttpPost post = new HttpPost(uri);
post.setEntity(new FileEntity(file, "text/html"));
HttpResponse httpResponse = client.execute(post);
int statusCode = httpResponse.getStatusLine().getStatusCode();

Uploading MS Word files from Android to .Net WCF?

I have problem in uploading .doc file to .Net WCF from my Android app. I am able to send file but it is not supported on WCF end.
Here is my method for uploading:
protected void checkinmethod(String rid) throws Exception {
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot, rid+".doc");
InputStream in = new FileInputStream(file);
byte[] bytearray=new byte[(int) file.length()];
int ab=0;
do
{
ab=in.read(bytearray, 0, bytearray.length);
} while(ab>0);
InputStream mystream= new ByteArrayInputStream(bytearray);
InputStreamEntity se=new InputStreamEntity(mystream, 10000);
HttpPost request = new HttpPost("http://10.66.52.247/tutorwcf/Service.svc/Service/updateMyDoc1");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/msword");
request.setEntity(se);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
statuss.setText(new String(buffer));
//
}
catch (Exception e) {
// TODO: handle exception
Log.e("hi", "exception is", e);
statuss.setText("exception");
}
}
here is .net code:
FileStream fileToupload = new FileStream("D:\\myfile.doc", FileMode.Create, FileAccess.Write);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = mystream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
return "success";
}
Please send links or code or any thing.
If you don't have idea about this please rank up this question..
thanks
public void checkinstream(String rid, String filename ) throws IOException
{
URL url=null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName= null;
existingFileName= "/mnt/sdcard/"+rid+".doc";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = Integer.MAX_VALUE;
String responseFromServer = "";
url = new URL("http://10.66.51.241/mywcf/Service.svc/Service/uploadMyDoc");
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// 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", "application/stream");
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)
{
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);
// close streams
Log.e("Debug",twoHyphens + boundary + twoHyphens + lineEnd);
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);
statuss.setText(str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
On the .net end create a wcf method which receives stream.
Thanks.

Categories

Resources