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 8122387
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T05:49:14+00:00 2026-06-06T05:49:14+00:00

I’m trying to upload an image file from an android device to my drupal

  • 0

I’m trying to upload an image file from an android device to my drupal website using services module

I can log-in succesfully:

HttpParams connectionParameters =  new BasicHttpParams(); 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(connectionParameters, timeoutConnection);                 
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(connectionParameters, timeoutSocket);

httpClient   =   new DefaultHttpClient(connectionParameters);
HttpPost httpPost       =   new HttpPost(serverUrl+"user/login");
JSONObject json = new JSONObject();    

try{
     json.put("password", editText_Password.getText().toString());
     json.put("username", editText_UserName.getText().toString());                          
     StringEntity se = new StringEntity(json.toString());
     se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

     httpPost.setEntity(se);                       

     //Execute HTTP post request
     HttpResponse response    =   httpClient.execute(httpPost);   
     int status_code = response.getStatusLine().getStatusCode();                            

     ... 
     ...

}
catch(Exception ex)
{

}

via response object I can get session name session id , user id and many other info.

after the login , I set no session info by myself through my HttpGet object , but use the same DefaultHttpClient, I can magically retrieve a node using the following code:

HttpGet httpPost2 = new HttpGet(serverUrl+"node/537.json");
HttpResponse response2 = httpClient.execute(httpPost2);

this made me think that, httpClient object stored the session info for me automatically.
because if I dont login first or use a new HttpClient object and try to retrieve the node, I get a 401 error.

However when I try to upload an image file as follows after logging in:

   httpPost = new HttpPost(serverUrl+"file/");
   json = new JSONObject();
   JSONObject fileObject = new JSONObject();    

   fileObject.put("file", photodata); //photodata is a byte[] that is set before this point
   fileObject.put("filename", "myfirstfile");
   fileObject.put("filepath", "sites/default/files/myfirstimage.jpg");
   json.put("file", fileObject);            

   se = new StringEntity(json.toString());
   se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
   httpPost.setEntity(se);      

   //Execute HTTP post request
   response    =   httpClient.execute(httpPost);   
   status_code = response.getStatusLine().getStatusCode();  

I get 401 error although I’m logged in and using the same HttpClient object.

I also tried adding :

httpPost.setHeader("Cookie", SessionName+"="+sessionID);

which again gives me 401 error.

I’m also not sure whether I’m using the correct url, because I’m trying to use file.create method, but writing the url as “myip:myport/rest/file/create” gives wrong address.
My aim is to upload an image to a users node, so I guess after succesfully adding the file, I’ll use node.create right?

I hope someone will help me get through this.

  • 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-06-06T05:49:16+00:00Added an answer on June 6, 2026 at 5:49 am

    I found when I first started doing this that most of my errors were due to not authenticating correctly.. I’m not sure your method is correct.. I know this works.

    Using Drupal Services 3, I login as such and then store my session cookie into shared preferences. dataOut is a JSON object which holds the needed user login, and password information.

    String uri = URL + ENDPOINT + "user/login";
    HttpPost httppost = new HttpPost(uri);
    httppost.setHeader("Content-type", "application/json");
    StringEntity se;
    try {
         se = new StringEntity(dataOut.toString());
         se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
         httppost.setEntity(se);
         HttpResponse response = mHttpClient.execute(httppost);
         mResponse = EntityUtils.toString(response.getEntity());
         // save the sessid and session_name
         JSONObject obj = new JSONObject(mResponse);
         SharedPreferences settings = PreferenceManager
        .getDefaultSharedPreferences(mCtx);
         SharedPreferences.Editor editor = settings.edit();
         editor.putString("cookie", obj.getString("session_name") + "="
                        + obj.getString("sessid"));
         editor.putLong("sessionid_timestamp", new Date().getTime() / 100);
         editor.commit();
    } catch { //all of my catches here }
    

    Once I have my session id stored.. I go about performing tasks on drupal like this.. The following code posts a node. I use the function getCookie() to grab the session cookie if it exists.. if not, then I log in, or if it’s expired, I log in. (note, you need to set the cookie expire time in your drupal settings.php file (I think that’s where it is if I remember correctly)

    String uri = URL + ENDPOINT + "node";
    HttpPost httppost = new HttpPost(uri);
    httppost.setHeader("Content-type", "application/json");
    String cookie = this.getCookie(mCtx);
    httppost.setHeader("Cookie", cookie);
    StringEntity se;
    try {
        se = new StringEntity(dataOut.toString());
    httppost.setEntity(se);
    HttpResponse response = mHttpClient.execute(httppost);
        // response is here if you need it.
    // mResponse = EntityUtils.toString(response.getEntity());
    } catch { //catches }
    

    The getCookie() function that keeps your cookie uptodate and working..

    /**
     * Takes the current time, the sessid and determines if we are still part of
     * an active session on the drupal server.
     * 
     * @return boolean
     * @throws InternetNotAvailableException
     * @throws ServiceNotAvailableException
     */
    protected String getCookie(Context ctx)
            throws InternetNotAvailableException {
        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(mCtx);
        Long timestamp = settings.getLong("sessionid_timestamp", 0);
        Long currenttime = new Date().getTime() / 100;
        String cookie = settings.getString("cookie", null);
                //mSESSION_LIFETIME is the session lifetime set on my drupal server
        if (cookie == null || (currenttime - timestamp) >= mSESSION_LIFETIME) {
    
                        // the following are the classes I use to login.
                        // the important code is listed above.
                        // mUserAccount is the JSON object holding login, 
                        // password etc.
            JSONObject mUserAccount = UserAccount.getJSONUserAccount(ctx);
            call(mUserAccount, JSONServerClient.USER_LOGIN);
    
            return getCookie(ctx);
        } else {
            return cookie;
        }
    }
    

    This really should enable you to take advantage of all that Services has to offer. Make sure your endpoints are correct, and also make sure your permissions are set. I cursed for hours before I realized I had not granted perms to make nodes to users.

    So once you are logged in.. To upload a file to Drupal Services I use the following code to first convert the image to byteArray.. and then to Base64.

    tring filePath = Environment.getExternalStorageDirectory()+ "/test.jpg";
    imageView.setImageDrawable(Drawable.createFromPath(filePath));
    Bitmap bm = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] byteArrayImage = baos.toByteArray(); 
    String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
    

    Once you have the encodedImage. Construct a JSON Object with the keys, file (required), filename (optional, but recommended), filesize (optional) and uid (optional, the poster I presume) JSON would therefore look like this at its simplist required form {“file”:encodedImage}. Then, after making sure you have enabled the file resource on your server, POST the data to my-server/rest-endpoint/file. The response will include a fid in JSON. You can then assign this fid to the image field of a node you subsequently create using the node resource.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I am trying to render a haml file in a javascript response like so:
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Does anyone know how can I replace this 2 symbol below from the string
I am using Paperclip to handle profile photo uploads in my app. They upload
I am using parse_ini_file to read the contents of a file however it is
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

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.