I am developing small android application in which I wanted to upload image from my android device to my server. I am using HttpURLConnection for that.
I am doing this in following way:
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(data);
bout.close();
I am using ByteArrayOutputStream but I don't know how to pass that data with my httpurlconnection. Is this the correct way to pass raw image data. I just wanted to send byte array which contains image data. No conversion or no multipart sending.
My code working fine without any error but it my server gives me reply
{"error":"Mimetype not supported: inode\/x-empty"}
I did this with httpclient using setEntity and its working fine with that. But I want to use urlconnection.
Am I doing something wrong? How to do this?
Thank you.
You must open the output stream connection and write the data in it.
You could try this:
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());
OutputStream outputStream = connection.getOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);
bout.close();
outputStream.close();
With this statement:
bitmap.compress(CompressFormat.JPEG, 100, bos);
You are doing two things: compress the bitmap and send the resulted data (the bytes that build the jpg) to bos stream, that send the resulted data to the output stream connection.
Also you can write the data in the output stream of the connection directly, replacing this:
ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);
With this:
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
I hope this helps you understand how HttpUrlConnection works.
Also, you should not load the whole bitmap entirely for avoid the "out of memory" exceptions, opening the bitmap with streams, for example.
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/six.3gp";
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://192.168.1.5/upload.php";
try
{
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
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=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
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);
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
tv.append(inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
/*while((str = inStream.readLine()) !=null ){
}*/
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
Complete Demo
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(ServerConstants.urll);
httppost.setHeader("Content-type","application/octet-stream");//application/octet-stream
// the below is the important one, notice no multipart here just the raw image data
httppost.setEntity(new ByteArrayEntity(imagebytess));
try {
HttpResponse res = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
res.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
System.out.println("Response: " + res.getStatusLine().getStatusCode());
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
System.out.println("Response: " + res.getStatusLine().getStatusCode());
}`enter code here`
System.out.println("Response: " + s.toString());
} catch `enter code here`(ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
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;
}
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;
}
I'm trying to upload image to webService but I couldn't do it and I searched lots of topics on here and on the internet but could't find good solution.
When I run this code I'm getting Bad Request error.
UPDATE : I used some codes that is in this link : Uploading MS Word files from Android to .Net WCF?
But giving me FileNotFoundException, but my file path is that : /mnt/sdcard/ImageDir/images/ilan_1360917248037__thumb_.jpeg
Here is my code that I'm trying :
public static String imgUpload(String url, List<NameValuePair> list, List<String> images){
String result = Constants.EMPTY;
Bitmap bm;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, ServiceConstant.TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, ServiceConstant.TIMEOUT_MILLISEC);
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost httppost = new HttpPost(url);
String resimYol = images.get(0);
resimYol = resimYol.replace("file:///", "/");
bm = BitmapFactory.decodeFile(resimYol);
Log.d("RESIL_YOL", resimYol.toString());
try{
ByteArrayBody bab = new ByteArrayBody(b, resimYol);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, resimYol);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.setEntity(reqEntity);
result = httpclient.execute(httppost,responseHandler);
}
catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
return result;
}
Here is my logcat :
02-12 11:43:07.467: E/org.apache.http.client.HttpResponseException(19112): Bad Request
try this example Link it might be help you.
and add all jar files which is required for this.
Try to convert the image in Base64 and then send its String response as a parameter to Web-service to make a successful upload to server.
public static String __imgUpload(String url, List<NameValuePair> list, List<String> images)
{
URL url1=null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName= null;
String urlServer = url;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String str = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = Integer.MAX_VALUE;
String responseFromServer = "";
try {
url1 = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
for(int resimID=0;resimID<images.size();resimID++)
{
existingFileName= images.get(resimID);
existingFileName = existingFileName.replace("file:///", "/");
try
{
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
conn = (HttpURLConnection) url1.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/stream");
dos = new DataOutputStream( conn.getOutputStream() );
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);
}
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 1: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error 2: " + ioe.getMessage(), ioe);
}
try {
inStream = new DataInputStream ( conn.getInputStream() );
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error 3: " + ioex.getMessage(), ioex);
}
}
return str;
}
This code definitely working.
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.
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.