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.
Related
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( )
I have made a form activity in android which contains some textfields and photo,I want to send this parameters to server
I am able to uplaod all other parameters successfully,But image is not uploading to server,Please help me save me..Thank you,My code is as below:
code
Bitmap bitmap;
onClick(){
editEnable();
System.out.println("::::::::::save clicked:::::::::");
header.edit.setVisibility(View.GONE);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// new EditProfileAPI().execute();
new ImageUploadTask().execute();
// Profile Edit Call...!!!
break;
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
private StringBuilder s;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... unsued) {
try {
String sResponse = "";
String url = Const.API_eDIT_PROFILE + "?";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("customer_id", new StringBody(Pref.getValue(HomeActivity.this, Const.PREF_CUSTOMER_ID, "")));
entity.addPart("first_name", new StringBody(et_firstname.getText().toString().trim()));
entity.addPart("last_name", new StringBody(et_lastname.getText().toString().trim()));
entity.addPart("customer_add", new StringBody(tv_adres.getText().toString().trim()));
entity.addPart("customer_phone", new StringBody(tv_phone.getText().toString().trim()));
entity.addPart("business_info", new StringBody(tv_busines.getText().toString().trim()));
entity.addPart("business_type", new StringBody(tv_busines_typ.getText().toString().trim()));
entity.addPart("bank_ac", new StringBody(tv_bank_acnt.getText().toString().trim()));
entity.addPart("dr_cr_card", new StringBody(tv_card.getText().toString().trim()));
entity.addPart("purpose_code", new StringBody(et_purpose_code.getText().toString().trim()));
entity.addPart("paypal_email", new StringBody(tv_paypal_email.getText().toString().trim()));
entity.addPart("password", new StringBody(et_fpassword.getText().toString().trim()));
entity.addPart("filename", new StringBody("test2.jpg"));
entity.addPart("files[]", new ByteArrayBody(data, "image/jpeg", "test2.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return s.toString();
} else {
return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String sResponse) {
try {
pDialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(), sResponse + " Photo uploaded successfully", Toast.LENGTH_SHORT).show();
System.out.println("::::::::::::::::::::::::::::MY SUCCESS RESPONESE in edit::::::::::::::::" + sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Upload image or media file
public void doFileUpload(String videoPath) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = videoPath;
String str = "";
System.out.println("(Talk)videoPath" + existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 1024 1024;
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
existingFileName));
// open a URL connection to the Servlet
URL url = new URL(url1);
// 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) {
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());
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
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 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();
}
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.