Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4531628
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T13:55:41+00:00 2026-05-21T13:55:41+00:00

Here i want to upload the pictures to the website. i listed the code

  • 0

Here i want to upload the pictures to the website.

i listed the code for that but which is doen’t work.

So plz help me to correct this.

MyImageUploader.java

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyImageUploader extends Activity{
    private static final int PICK_IMAGE = 1;
    private ImageView imageview;
    private TextView textview;
    private Button button;
    private EditText edittext;
    private Bitmap bitmap;
    private ProgressDialog dialog;
    String albumId = ConstantData.album_id;
    Integer userId = ConstantData.userId;
    Bitmap photoId; 
    ArrayList<Object> result;
    XmlParser parser;
    HttpResponse response;
    InputStream in;
    String strResponse;
    HttpPost post;
    int width_tmp,height_tmp;
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myimageuploader);

        imageview = (ImageView)findViewById(R.id.upldimgvw);
        button = (Button)findViewById(R.id.btn_imgupld);
        edittext = (EditText)findViewById(R.id.edt_cptn);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(bitmap == null){
                    Toast.makeText(getApplicationContext(), "Please select image..", Toast.LENGTH_SHORT).show();
                }
                else{
                    dialog = ProgressDialog.show(MyImageUploader.this, "Uploading", "Please wait...",true);
                    new ImageUploadTask().execute();
                }
            }
        });
    }
     public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.imageupload_menu, menu);
        return true;
    }
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
            case R.id.ic_menu_gallery:
                try{
                    Intent intent = new Intent();
                    intent.setType("Image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
                }catch (Exception e) {
                // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "Get Picture" ,Toast.LENGTH_SHORT).show();
                    Log.e(e.getClass().getName(),e.getMessage(),e);
                    break;
                }
                return true;
            case R.id.ic_menu_Images:     
                Toast.makeText(this, "You pressed the Image!", Toast.LENGTH_LONG).show();
                break;
         }
        return super.onOptionsItemSelected(item);
        }

    protected void onActivityResult(int requestcode,int resultcode, Intent data){
        Log.i("Request Code",""+requestcode);
        Log.i("Result Code", ""+resultcode);
        Log.i("Intent Data",""+data);
        switch(requestcode){
        case PICK_IMAGE:
            if(resultcode == Activity.RESULT_OK);
            Uri selectedImageUri = data.getData();
            String filePath = null;
            try{
                String filemanagerstring = selectedImageUri.getPath();
                String selectedImagePath = getPath(selectedImageUri);
                if(selectedImagePath != null)
                {
                    filePath = selectedImagePath;
                }else if(filemanagerstring != null)
                {
                    filePath = filemanagerstring;
                }else{
                    Toast.makeText(getApplicationContext(), "Unknown Path",Toast.LENGTH_SHORT).show();
                    Log.e("Bitmap","Unknown Path");
                }
                if(filePath != null){
                    decodeFile(filePath);
                }
                else{
                    bitmap = null;
                }
            }catch (Exception e) {
                // TODO: handle exception
                Toast.makeText(getApplicationContext(), "Internal Error", Toast.LENGTH_SHORT);
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }   

    }

    class ImageUploadTask extends AsyncTask<Void, Void, String>{
        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
                try{
                    DefaultHttpClient client = new DefaultHttpClient();
                    post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=album_list&upload_photo&userid=80&sessionid=3011e063260d55b8a7095bc3a581130c&tmpl=component 14:34");
                    StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><photo>"+photoId+"</photo></data>");
                    StringEntity strEntity = new StringEntity(strBuffer.toString());
                    post.setEntity(strEntity);

                    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(CompressFormat.JPEG, 100, bos);
                    byte[] data = bos.toByteArray();
                    entity.addpart("userId");
                    entity.addPart("albumId");
                    entity.addPart("photoId", new FileBody(new File(filepath)));
                    post.setEntity(entity);
                    response = client.execute(post);
                    in = response.getEntity().getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                    strResponse = convertStreamToString(in);
                    parser = new XmlParser(in, new AddAlbumDetailBean());
                    result = parser.parse("data", "photo");
                }catch (Exception e){
                    if (dialog.isShowing())
                        dialog.dismiss();
                        Toast.makeText(getApplicationContext(),"image",Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
            return null;
        }
                return albumId;
        }
        }
    protected void onPostExecution(String strResponse){
            try{
                if(dialog.isShowing())
                    dialog.dismiss();
                if(strResponse != null)
                {
                    Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getApplicationContext(), "Photo Uploaded Successfully", Toast.LENGTH_SHORT).show();
                    edittext.setText("");
                }


                }catch (Exception e) {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(),"Exception Image", Toast.LENGTH_SHORT).show();
                                Log.e(e.getClass().getName(), e.getMessage(), e);
                }
    }


    public String getPath(Uri uri){
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor != null){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else{
            return null;
        }
    }
    public void decodeFile(String filePath){
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath,o);

        final int REQUEST_SIZE = 1024;
        int width_tmp = o.outWidth,height_tmp = o.outHeight;
        int scale = 1;
        while(true){
        //  if(width_tmp &lt;REQUEST_SIZE &amp;&amp; height_tmp &lt; REQUEST_SIZE){
                //break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
        //  }
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFile(filePath,o2);
            imageview.setImageBitmap(bitmap);
        }

    }
    public String convertStreamToString(InputStream in)
    throws IOException {


        if (in != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(in, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                // in.close();
            }
            return writer.toString();
        } else { 
            return "";
        }
    }
}

Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T13:55:42+00:00Added an answer on May 21, 2026 at 1:55 pm

    use this function to upload. Please pass path ur file as argument.

    public void uploadImage(String fileName)
    {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;
    
        String pathToOurFile = fileName;
        String urlServer = GlobalHandler.getImageUploadUrl();
        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(pathToOurFile) );
    
        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();
    
        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
    
        // Enable POST method
        connection.setRequestMethod("POST");
    
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        if(GlobalHandler.getUserId()!=null)
            connection.addRequestProperty("user_id", GlobalHandler.getUserId());
        else
            connection.addRequestProperty("user_id", "007");
    
        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"upload_file\";  filename=\"" + pathToOurFile +"\"" + 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)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        }
        catch (Exception ex)
        {
        //Exception handling
    
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

enter code here Want to remove items from a Main list , but give
Here's I want to do, I want to upload a file that will be
i want to upload two files. here is the script <? ini_set('memory_limit', 400M); ini_set('file_uploads',
I want to upload a csv file into a sql table. Here is my
i have the form, and i want to upload two files. here is the
Need a little help with my jquery here I want all my button with
I'm not entirely sure if I can do what I want here, but I
Please find the code at http://jsfiddle.net/wlogeshwaran/NGL8P/4/ Here i want to make the 'hi' ,
I use Uploadify to upload multiple pictures to server. I want to display pictures
I want to upload two images to the server with following code can any

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.