Android - Send Image file to the Server DB
Asked Answered
M

4

6

Users save three data: name, note and image. As you can see the code below, I succeeded to code to send the name and note to the server side. But, I have no idea how to send a selected image file from the device to the serverDB.

public class AddEditWishlists extends Activity {

    // Client-Server - Start //////////////////////
    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = 
        "http://10.56.43.91/android_connect/create_product.php";


    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    // Client-Server - End //////////////////////


    //Define Variables
    private EditText inputname;
    private EditText inputnote;
    private Button upload;
    private Bitmap yourSelectedImage;
    private ImageView inputphoto;
    private Button save;
    private int id;
    private byte[] blob=null;
    byte[] image=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_wishlist);
        setUpViews();
    }

    private void setUpViews() {

        inputname = (EditText) findViewById(R.id.inputname);
        inputnote = (EditText) findViewById(R.id.inputnote);
        inputphoto = (ImageView) findViewById(R.id.inputphoto); 

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            id=extras.getInt("id");
            inputname.setText(extras.getString("name"));
            inputnote.setText(extras.getString("note"));

            image = extras.getByteArray("blob");

            if (image != null) {
                if (image.length > 3) {
                    inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
                }
            }

        }



        //Image Upload Button
        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            }
        });

        // Save the data
        save = (Button) findViewById(R.id.save);

        // Save하면 발생되는 이벤트
        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (inputname.getText().length() != 0) {
                    AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                        @Override
                        protected Object doInBackground(Object... params) {
                            saveContact();

                            // Client-Server - Start //////////////////////////////////////
                            String name = inputname.getText().toString();
                            String description = inputnote.getText().toString();


                            // Building Parameters
                            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                            params1.add(new BasicNameValuePair("name", name));
                            params1.add(new BasicNameValuePair("description", description));

                            // getting JSON Object
                            // Note that create product url accepts POST method
                            JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                            // check log cat fro response
                            Log.d("Create Response", json.toString());

                            // check for success tag
                            try {
                                int success = json.getInt(TAG_SUCCESS);

                                if (success == 1) {
                                    // successfully created product
                                    // closing this screen
                                    finish();
                                } else {
                                    // failed to create product
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            // Client-Server - End ////////////////////////////////////

                            return null;
                        }

                        @Override
                        protected void onPostExecute(Object result) {
                            finish();
                        }
                    };

                    saveContactTask.execute((Object[]) null);

                } else {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            AddEditWishlists.this);
                    alert.setTitle("Error In Save Wish List");
                    alert.setMessage("You need to Enter Name of the Product");
                    alert.setPositiveButton("OK", null);
                    alert.show();
                }
            }
        });
    }


    // If users save data, this will act (data -> db) 
    private void saveContact() {

        if(yourSelectedImage!=null){
            ByteArrayOutputStream outStr = new ByteArrayOutputStream();
            yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
            blob = outStr.toByteArray();
        }

        else{blob=image;}

        // Change Text type to string type to save in the DB
        SQLiteConnector sqlCon = new SQLiteConnector(this);

        if (getIntent().getExtras() == null) {
            sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
        }

        else {
            sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
        super.onActivityResult(requestCode, resultCode, resultdata);
        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = resultdata.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);

                cursor.close();
                // Convert file path into bitmap image using below line.
                yourSelectedImage = BitmapFactory.decodeFile(filePath);
                inputphoto.setImageBitmap(yourSelectedImage);
            }

        }
    }

}

How can I code between the client-server annotation to send the image file?..

Moreville answered 8/5, 2013 at 17:35 Comment(6)
Use http-request. See github.com/kevinsawicki/….Frigg
yes, i already used http post request to send name and note to the server DBMoreville
my question is how to send image files to the server using http requestMoreville
I don't see in your code that you're using http-request library. The link is the example on how to send a file to a server.Frigg
check this line "JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);"Moreville
I made JSONParser class seperately.Moreville
S
6

You can convert the selected image to base 64 string and then pass that string to the server and then in the server decode that,

Check this code to convert image to base64,If you have the imageView then you can write this code,

imageView.buildDrawingCache();
Bitmap bm = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b , Base64.DEFAULT);

EDIT

as in your code,you have the byte array in this line,

image = extras.getByteArray("blob");

so you can directly write this line of code after that,

String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);
Shocker answered 8/5, 2013 at 17:47 Comment(25)
@junghur check my edited answer, if you have the imageview then you can get the base64 string as above.You can write this code after you get the selected image in imageview.Shocker
what should i do if i dont have the imageviewMoreville
You dont need image view, in your code you have byte array, so just use Base64 class to get the base64 string, see my edited answer.Shocker
Actually you dont need the first code,that could be used if you had the imageview, take the second one.Shocker
second one means "String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);" this one?Moreville
When i added "String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);" this line, "DEFAUL" makes error. why?Moreville
succeeded to receive the photo in the server DB!! but it looks like thisMoreville
"com.example.philips.AddEditWishlists@41bcf568" how can i save the file into the jpg file in my laptop(server)?Moreville
The error might be because the minimum sdk level required for this is 8,so change it to 8 in your manifest.Also the encoded string should not look like "com.example.philips.AddEditWishlists@41bcf568" it should look something like "46c6pbLHIlsos2JdLYhlZ5cbH3E8SD5gfbkg5mXxHdR2/wDwipZPOEf9j7PJy.........and many more". Check your code.Once you convert that image to string, have a check by printing that string.Also in the server side you can google for how to convert base64 string to byte array and then back to image in your server side language,you will get a lot of threads.Shocker
thank you for your kind answer! Btw, on the server side of DB, name is sent by varchar, description is sent by text..what about the photo then? should it be binary form? or..what..?Moreville
And actually, on the server side, I succeeded to be saved the photo, but it's empty file...Moreville
do you know what the problem is..bro..?Moreville
can you check this link please? #16540738Moreville
make it sure you are sending the same encoded string because in the onclick method of save button, you are overriding the value of encoded stringShocker
I received the string format like this "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQE"Moreville
but in my directory, there are still empty file is saved! any suggestion please?Moreville
yes you are getting the right string now, there must be something wrong in converting that String back to image.How are you doing that.search for how to convert base64 string to byte array and then back to image in php.Shocker
do you know php? could you please check this link? #16544253Moreville
you are my last hope...i have been working on this 2weeks already... :(..wanna cry....Moreville
do i need to convert base64 string to byte array on server side(php) or client side(android)?Moreville
hey dont worry. Read this stackoverflow thread #9921467 the same scenario as yours.I am sure you will get your answer here.Shocker
bro!!!! I received the file in my directory!!! but the only problem is that i received only the file..not with jpg. So, I need to rename it like filename -> filename.jpgMoreville
any suggestion to receiving jpg file automatically so that i don't need to rename it???Moreville
man, finally i did it!!! man...after more than 2 weeks...i did it...so thank you and appreciate with your help!!Moreville
While this answer works, it's not really optimal for a production environment where you can't control the what kind and size of images the users want to upload; reason being, if the user selects a very large image in terms of size, you'll easily get a 'OutOfMemoryException' with this solution. Read more on Multipart uploads; they provide ideal solution.Doering
D
2

I use the following code to upload image to php server. Notice uploadFile function you just have to pass your path of image from sdcard.

public class PhotosActivity extends Activity {
    ImageView img, img1;
    int column_index;
    Intent intent = null;
    Bitmap bitmap = null;
    FileInputStream in1, in2, in3;
    BufferedInputStream buf;
    // Declare our Views, so we can access them later
    String logo, imagePath, Logo;
    Cursor cursor;

    private String Tag = "UPLOADER";
    private String urlString = "YOUR_ONLINE_PHP";
    HttpURLConnection conn;
    // YOU CAN EDIT THIS TO WHATEVER YOU WANT
    private static final int SELECT_PICTURE = 1;

    String selectedImagePath;
    // ADDED
    String filemanagerstring;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos1_layout);
        // ListView iv= (ListView)findViewById(R.id.listView1);
        // iv.setAdapter(new ArrayAdapter(this,
        // android.R.layout.simple_list_item_1, values));
        // iv.setAdapter(new
        // ArrayAdapter(this,android.R.layout.simple_list_item_1, values));
        img = (ImageView) findViewById(R.id.imageView1);

    }

    public void onClick(View v) {
        // select a file
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                SELECT_PICTURE);

    }

    String path = "";


    // UPDATED
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();

                // OI FILE Manager
                filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                selectedImagePath = getPath(selectedImageUri);

                img.setImageURI(selectedImageUri);

                imagePath.getBytes();
                path = imagePath.toString();
                // TextView txt = (TextView)findViewById(R.id.title);
                // txt.setText(imagePath.toString());

                Bitmap bm = BitmapFactory.decodeFile(imagePath);

                uploadFile(imagePath.toString());

            }

        }

    }

    public int uploadFile(String sourceFileUri) {
        String upLoadServerUri = "http://"+common.ipaddress+"/database/upload.php";
        String fileName = sourceFileUri;
        int serverResponseCode = 0;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File Does not exist");
            return 0;
        }
        try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                                                                // connection to
                                                                // the URL
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available(); // create a buffer of
                                                            // maximum size

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

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
                    + ": " + serverResponseCode);
            if (serverResponseCode == 200) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        // tv.setText("File Upload Completed.");
                        Toast.makeText(PhotosActivity.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Toast.makeText(PhotosActivity.this, "MalformedURLException",
                    Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(PhotosActivity.this,
                    "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        return serverResponseCode;
    }

    // UPDATED!
    public String getPath(Uri uri) {
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        imagePath = cursor.getString(column_index);

        return cursor.getString(column_index);
    }
}

and in php

$target_path1 = "upload/";

$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)

Hope that helps

Dishevel answered 8/5, 2013 at 21:42 Comment(3)
why is it too long, and this code doesn't match with my code i guess...no..?Moreville
I am getting a null exception right at dos = new DataOutputStream(conn.getOutputStream());Noelianoell
@Noelianoell Did you remember to set conn.setRequestMethod("POST") and conn.setDoOutput(true)? If so, maybe your conn object is null? Your stack trace should have more clues.Veneaux
E
0
public class AddPost extends ActionBarActivity {
protected ImageButton imgButton;// To refer image button
protected ImageView image;

// To refer image view
protected ImageButton ImageFromCard;
private static int RESULT_LOAD_IMAGE = 2;

private ProgressDialog PDialog;
Button btnLogout;
@SuppressWarnings("unused")
private boolean imgCapFlag = false;
protected boolean taken;
protected static final String PHOTO_TAKEN = "photo_taken";
protected String path;
private Bitmap bitmap;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_post);

    image = (ImageView) findViewById(R.id.image);

    imgButton = (ImageButton) findViewById(R.id.imageButton1);
    imgButton.setOnClickListener(new ButtonClickHandler());
    ImageFromCard = (ImageButton) findViewById(R.id.imageButton2);

    path = Environment.getExternalStorageDirectory()
            + "/images/make_machine_example.jpg";

    // ---------------------MEMORY CARD OPEN----------------------------

    ImageFromCard.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });

    // ------------------URL FOR CATEGORIES--------------------

}

public void seepost(View view) {
    Intent i = new Intent(view.getContext(), MainActivity.class);
    startActivity(i);
}

// ---------Handling Image Result---------------------

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        BitmapFactory.Options options = new BitmapFactory.Options();
        bitmap = BitmapFactory.decodeFile(picturePath);
        // Set ImageView with the bitmap read in the prev line
        image.setImageBitmap(bitmap);

    } else {

        // Log message
        Log.i("SonaSys", "resultCode: " + resultCode);
        switch (resultCode) {
        // When user doesn't capture image, resultcode returns 0
        case 0:
            Log.i("SonaSys", "User cancelled");
            break;
        // When user captures image, onPhotoTaken an user-defined method to
        // assign the capture image to ImageView
        case -1:
            onPhotoTaken();
            break;

        }

    }

}

// ----------------------------------------------------

public class ButtonClickHandler implements View.OnClickListener {
    public void onClick(View view) {
        // Below log message will be logged when you click Take photo button
        Log.i("SonaSys", "ButtonClickHandler.onClick()");
        // Call startCameraActivity, an user defined method, going to be
        // created
        startCameraActivity();
    }
}

protected void startCameraActivity() {
    // Log message
    Log.i("SonaSys", "startCameraActivity()");
    // Create new file with name mentioned in the path variable
    File file = new File(path);

    Uri outputFileUri = Uri.fromFile(file);
    Intent intent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(intent, 0);
}

protected void onPhotoTaken() {
    // Log message
    Log.i("SonaSys", "onPhotoTaken");
    // Flag used by Activity life cycle methods
    taken = true;
    // Flag used to check whether image captured or not
    imgCapFlag = true;
    // BitmapFactory- Create an object
    BitmapFactory.Options options = new BitmapFactory.Options();
    // Set image size
    options.inSampleSize = 4;
    // Read bitmap from the path where captured image is stored
    bitmap = BitmapFactory.decodeFile(path, options);
    // Set ImageView with the bitmap read in the prev line
    image.setImageBitmap(bitmap);

}

// ----------------Image Upload ------------------------------

public void postData(View view) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://sitename.net/controllername/post");

    try {

        if (bitmap != null) {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            String file = Base64.encodeBytes(data);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    7);

            nameValuePairs.add(new BasicNameValuePair("image", file));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            httpclient.execute(httppost);

        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}
Exotic answered 16/10, 2014 at 10:6 Comment(0)
E
0
 # handling in Asp.Net MVC #

 public string Post( string PostText, byte[] image)
      {
        PostCS PostCs = new PostCS();
        ImageResize obj = new ImageResize();
        string FileName = DateTime.Now.ToFileTime().ToString().Trim();
        string imgName;        

        if (image != null)
        {
            ImageFormat png = ImageFormat.Png;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(image))
            {
                System.Drawing.Image bp = System.Drawing.Image.FromStream(ms, true);
                //Bitmap bp = new Bitmap(Image.FromStream(ms));
                imgName = FileName + "_" + bp.Width + "X" + bp.Height + ".png";
                bp.Save(Server.MapPath(ConfigurationManager.AppSettings["WallPostImages"].ToString()) + imgName, png);
                PostCs.ImageName = imgName;                   
                PostCs.InsertPostImg(PostCs);


            }
            var resizemaster = from a in LQdb.Z_ImageSetups select a;
            int wallwidth = 640;
            int wallheight = 480;             

            string orginalfilename = Server.MapPath(ConfigurationManager.AppSettings["WallPostImages"].ToString()) + imgName;
            obj.ImageStream(FileName, ConfigurationManager.AppSettings["WallPostImages"].ToString(), wallwidth, wallheight, orginalfilename, out imgName);
            PostCs.ImageName = imgName;
            PostCs.ImageType = "Wall";
            PostCs.InsertPostImg(PostCs);


        }
        return PostText;
    }
Exotic answered 16/10, 2014 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.