Skip to content Skip to sidebar Skip to footer

Android Multipart File Upload With Access Token

I want to send access token as a multipart data along with the file to the php server. I wrote the following code but it is giving 401 Unauthorized error. I think I am not passing

Solution 1:

It depends on server configuration. In general, if you need to pass a authorization token with your Http POST, its passed with the header with setHeader. Here's my working code snippet for multi-part file upload.

HttpClientclient=newDefaultHttpClient();
Filefile=newFile(selectedImagePath);
HttpPostpost=newHttpPost(uploadUrl);

post.setHeader("token", myAuthToken);
post.setHeader("Content-type", "multipart/form-data; boundary=" + boundary);
MultipartEntityentity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    Constants.BOUNDARY, Charset.defaultCharset());

entity.addPart(Constants.MULTIPART_FORM_DATA_NAME, newFileBody(file));
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

post.setEntity(entity);

HttpResponseresponse= client.execute(post);
HttpEntityhttpEntity= response.getEntity();
Log.d("Response", EntityUtils.toString(httpEntity));

Solution 2:

Working copy of Multipart image upload using service:

private MutipartImageUploadModel handleUploadAction(int tileId) {
        StringimageName= getTilesInUploadPath(this, fileId);
        if (imageName == null) {
            returnnull;
        }
        InputStream responseInputStream;
        try {
            FilefilesDir= getApplicationContext().getFilesDir();
            FileimageFile=newFile(filesDir, imageName);
            HttpClienthttpClient=newDefaultHttpClient();
            HttpContextlocalContext=newBasicHttpContext();
            doublebytes= imageFile.length();
            HttpPosthttpPost=newHttpPost(ServiceConstantInterface.URL_UPLOAD_IMAGE);            httpPost.setHeader(ServiceConstantInterface.Authorization_KEY, ServiceConstantInterface.Authorization_KEY_VALUE);
            httpPost.setHeader("SessionKey", newSharedPrefDataSupplier(this).getmSessionKey());
            MultipartEntityBuilderentityBuilder= MultipartEntityBuilder.create();
            entityBuilder.addPart("file_name", newFileBody(imageFile));
            entityBuilder.addPart("file_id", newStringBody(String.valueOf(fileId)));
            entityBuilder.addPart("SessionKey", newStringBody(newSharedPrefDataSupplier(getApplicationContext()).getmSessionKey()));
            HttpEntityentity= entityBuilder.build();
            httpPost.setEntity(entity);
            HttpResponseresponse= httpClient.execute(httpPost, localContext);
            StatusLinestatusLine= response.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                responseInputStream = response.getEntity().getContent();
                if (responseInputStream != null) {
                    Readerreader=newInputStreamReader(responseInputStream);
                    Gsongson=newGsonBuilder().create();
                    MutipartImageUploadModelwResponse= gson.fromJson(reader, MutipartImageUploadModel.class);
                    Log.i(TAG, "Response " + wResponse);
                    try {
                        reader.close();
                        responseInputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return wResponse;
                }
            } else {
                Log.i(TAG, "Server responded with status code: " + statusLine.getStatusCode());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        returnnull;
    }

Solution 3:

If you plan to send some headers, access tokens, cookies then you should set it in the request properties part like:

// Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            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("file", fileName);
            **conn.setRequestProperty("COOKIE_NAME_OR_TOKEN", mToken);**

Post a Comment for "Android Multipart File Upload With Access Token"