Tuesday 3 April 2012

Uploading heavy file (image, document or mp3) to restful wcf with Streaming from android

Hi
In this post is i have explained how to upload file from android to restful wcf.

class CheckInAsync extends AsyncTask<String, String, String> {

            HttpEntity responseEntity = null;

            OutputStream mystream;

            String resposeCheckin = new String();
            String existingFileName = "/mnt/sdcard/abtemp/" + objrid
                    + fileExtension;
            private Activity context;
            private FragmentManager fmgr;

            

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                
               
            }

            @Override
            protected String doInBackground(String... param) {
                if ((isOnline(ObjectDescriptionActivity.this).equals("true"))) {
                    try {



                        URL url = null;
                        HttpURLConnection conn = null;
                        DataOutputStream dos = null;
                        DataInputStream inStream = null;

                        StringBuffer sb;

                        int bytesRead, bytesAvailable;

                        int maxBufferSize = Integer.MAX_VALUE;
                        try {


                            url = new URL(
                                    getResources().getString(R.string.ServiceBaseUrl)+
                                   "ServiceMobile.svc/Service/uploadRequestMobile?"
                                            +"param0="                                   
                                            + param[0]
                                            + "&param1="
                                            + param[2]
                                            + "&param2="
                                            + param[1]
                                            + "&filename="
                                            + param[4]
                                            + "&fileExtension="
                                            + param[5]
                                            + "&param3="
                                            + param[3]);
                           
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.gc();

                        try {
                            // ------------------ CLIENT REQUEST
                            File file = new File(existingFileName);

                            if (file.isFile()) {
                                FileInputStream fileInputStream = new FileInputStream(
                                        file);                           
                                // Open a HTTP connection to the URL
                                conn = (HttpURLConnection) url.openConnection();
                                // Allow Inputs
                                conn.setDoInput(true);
                                // Allow Outputs
                                conn.setDoOutput(true);
                                // Don't use a cached copy.
                                conn.setUseCaches(false);
                                // Use a post method.
                                conn.setRequestMethod("POST");                      

                                maxBufferSize = 6 * 1024;




                               conn.setFixedLengthStreamingMode((int) file.length());
                             // works fine till 24 mb file
                                conn.setRequestProperty("Connection", "Keep-Alive");
                                conn.setRequestProperty("Content-Type",
                                        "application/stream");

                                dos = new DataOutputStream(conn.getOutputStream());

                                bytesAvailable = fileInputStream.available();
                                int bufferSize = Math.min(bytesAvailable,
                                        maxBufferSize);
                                bytesAvailable = fileInputStream.available();

                                bufferSize = Math
                                        .min(bytesAvailable, maxBufferSize);

                                byte[] buffer = new byte[bufferSize];


                                bytesAvailable = fileInputStream.available();
                                int downloadedSize = 0;
                                while ((bufferSize = fileInputStream.read(buffer)) > 0) {

                                    dos.write(buffer, 0, bufferSize);

                                    downloadedSize += bufferSize;
                                   
                                e

                                }
                                String lineEnd = "";

                                dos.writeBytes(lineEnd);


                                fileInputStream.close();
                                dos.flush();
                                dos.close();
                            } else {
                                return "file not found";
                            }
                        } catch (MalformedURLException ex) {
                            Log.e("Debug", "error: " + ex.getMessage(), ex);
                        } catch (IOException ioe) {
                            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
                        }
                        // ------------------ read the SERVER RESPONSE
                        try {
                            inStream = new DataInputStream(conn.getInputStream());
                            String str = new String();
                            sb = new StringBuffer(str);
                            while ((str = inStream.readLine()) != null) {
                                sb.append(str);


                            }
                            inStream.close();
                 Log.e("Debug","Server Response "+sb.toString());
                            resposeCheckin = new String(sb);

                        }

                        catch (IOException e) {

                            resposeCheckin = "UnSuccess";
                             e.printStackTrace();
                        }

                        String str_raj = resposeCheckin.substring(1,
                                resposeCheckin.length() - 1);

                        Log.e("hhguyuyjjhyjhjyhjhjhjh", str_raj);

                        return str_raj;

                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                        return "Sorry,Illegal state error";
                    } 
                }
                return null;

            }

            protected void onProgressUpdate(String... progress) {
                

            }

            @Override
            protected void onPostExecute(String responsestr) {
               
            }
        }

And on the .net (wcf end) define a OperationContact as:

[OperationContract]//(IsOneWay = true)
         [WebInvoke(RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
          UriTemplate = "/ProcessCheckInRequestMobile? param0 ={ param0}& param1 ={ param1}& param2 ={ param2}&filename={filename}&fileExtension={fileExtension}& param3={ param3}")]
                string ProcessCheckInRequestMobile(string param0, string  param1 , string  param2 , string filename,string fileExtension, long  param3 , Stream data);



No comments:

Post a Comment