1

I am developing a android app. In this app need to upload image to imageShack site using their api.

Here "sourceFileUri" is image file path which come from sdcard of the device.It shows Outh or dev Key is invalid.. Please can anyone help me to find out the error. Advanced Thanks.

private void goForUpload(final String sourceFileUri)
{
    if (!SharedPreferencesHelper.isOnline(con))
    {
        return;
    }

    pDialog = ProgressDialog.show(this, "Please wait...", "Loading...",false, false);

    final Thread d = new Thread(new Runnable() 
    {
        @Override
        public void run() {

            String upLoadServerUri = " http://www.imageshack.us/upload_api.php";

            String fileName = sourceFileUri;

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

            Log.w("file name are...", "" + sourceFile);
            if (!sourceFile.isFile()) {
                Log.e("uploadFile", "Source File Does not exist");
            }

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

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

                dos.writeBytes("Content-Disposition: form-data; name=\"key\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes("289DGHSTbbfb01094c0017d23e96fe1edecda161");
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);


                bytesAvailable = fileInputStream.available(); 

                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();
                InputStream servere = conn.getInputStream();
                String uyy = HttpRequest.GetText(servere);

                System.out.print(uyy);

                Log.w("uyy", "" + uyy);

                Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) 
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            Toast.makeText(MainActivity.this,"File Upload Complete.",Toast.LENGTH_SHORT).show();
                        }
                    });
                }

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

                // Log.w("url", ""+url);

                // final String url =
                // "http://www.imageshack.us/upload_api.php?fileupload=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg&url="+fos+"&optsize=100x100&rembar=yes&key=DHKNPRWYb185051e16c4545d8f26828d6fd3886c";

                // final String url =
                // "https://api.mobypicture.com/2.0/upload.json";//key=Az7IN9Qaxu3eZeK5/media=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg/message=wasir";
                //
                // final String result = HttpRequest.GetText(HttpRequest
                // .getInputStreamForGetRequest(url));
                //
                // try {
                // if (parser.connect(con, result)) {
                // Log.d("What is result :", result);
                // }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*
             * update the GUI
             */

            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    if (pDialog != null) {
                        pDialog.cancel();
                    }
                }

            });

        }
    });

    d.start();

}
Terrance
  • 11,764
  • 4
  • 54
  • 80
Wasir
  • 185
  • 2
  • 11
  • dev Key is invalid -> are you sure you dev key of ImageShack is valid? – Tobrun Dec 07 '12 at 14:51
  • Yes, Because i can upload image using this api key by browser. – Wasir Dec 08 '12 at 05:31
  • 12-08 11:31:14.417: W/Respone(9988): 12-08 11:31:14.417: W/Respone(9988):** You must provide a valid auth token or dev key. see http://code.google.com/p/imageshackapi/** 12-08 11:31:14.417: W/Respone(9988): – Wasir Dec 08 '12 at 05:33
  • This is the error show in logcat – Wasir Dec 08 '12 at 05:34
  • Where you able to figure this out? I tried implementing your code and solution below. I had to comment out all the HttpRequest stuff because it was invalid. So I couldn't read my response text. But I was able to submit and received response code 200, however the pictures never make it to the sight. Very frustrating. Any tips would be appreciated – BriCo84 May 21 '13 at 03:43

1 Answers1

1

First Issue is the order you have your form-data parts:

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

            //for image
            dos.writeBytes("Content-Disposition: form-data; name=\"fileupload\";filename=\""+ fileName + "\"" + lineEnd);
                dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
                dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            dos.writeBytes(lineEnd);
            //dos.writeBytes(twoHyphens + boundary + lineEnd);

Second issue (when I tried) was that image type was invalid, so I added the content-type as seen above. And you didn't need the boundary before writing the file contents.