0

I've been looking for a way to upload a file using Volley API using the PUT method. All I've seen so far are through MultiPart POST method which aren't applicable to my case.

Assuming I can't change anything on the server side and I'm stuck with using PUT. How do I achieve this in volley?

Note that I only have the url where to upload the file and the file itself.

kishidp
  • 1,918
  • 6
  • 23
  • 29
  • To my understanding, PUT And POST are similar (Not the same). http://stackoverflow.com/questions/630453/put-vs-post-in-rest However, I think you should be able to change the answers on stackoverflow from POST to PUT and it should still work ? http://stackoverflow.com/a/36891462/940834 – IAmGroot Nov 10 '16 at 09:34
  • hmm ok will check this one. though not sure about what to replace in the params part as I don't have anything as params. I'll not override it I guess. will update for the result – kishidp Nov 10 '16 at 09:45
  • If you don't have any params, then you wont need to set any. Just the file itself. – IAmGroot Nov 10 '16 at 09:51
  • @kishidp were you able to do so? – WISHY Apr 17 '19 at 14:20

2 Answers2

0

For uploading image file add the following functions to your StringRequest object. Here outputFileUri is the Uri of the file which you want to upload.

        @Override
        public String getBodyContentType() {
            return "image/jpeg";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                InputStream inputStream = mContext.getContentResolver().openInputStream(outputFileUri);
                byte[] b = new byte[8192];
                for (int readNum; (readNum = inputStream.read(b)) != -1; ) {
                    bos.write(b, 0, readNum);
                }
                inputStream.close();
                return bos.toByteArray();
            } catch (Exception e) {
                Log.d(TAG, e.toString());
            }
            return null;
        }
Deepak
  • 71
  • 4
-1

use the basic concept of PUT method

url = "your URL";

StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
new Response.Listener<String>() 
{
    @Override
    public void onResponse(String response) {
        // response
        Log.d("Response", response);
    }
}, 
new Response.ErrorListener() 
{
     @Override
     public void onErrorResponse(VolleyError error) {
                     // error
         Log.d("Error.Response", response);
   }
}){

@Override
protected Map<String, String> getParams() 
{  
        Map<String, String>  params = new HashMap<String, String> ();  
        params.put("name", "file_name");  

        return params;  
}
}; RequestQueue queue = Volley.newRequestQueue(this);
queue.add(putRequest);
Sam
  • 45
  • 1
  • 8