1

I have found this method to upload image from device to server. It all works great, but I would also like to send some additional string params with image. Being a noob I find it difficult to attach them to this method. I could send string parameters via url that much I have learned so far, but I would really like to send them along with image

public int uploadFile(String sourceFileUri) {
        String upLoadServerUri = "http://www.mywebsite.com/web_services/ws_newitem.php";
        String fileName = "IMG_TEST.jpg";
    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);

    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }

    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);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of
                                                        // maximum size

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

        Log.i("uploadFile", "HTTP Response</span> is : "
                + serverResponseMessage + ": " + serverResponseCode);
        if (serverResponseCode == 200) {
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText("File Upload Completed.");
                    Toast.makeText(UploadToServer.this,
                            "File Upload Complete.", Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }

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

    } catch (MalformedURLException ex) {
        dialog.dismiss();
        ex.printStackTrace();
        Toast.makeText(UploadToServer.this, "MalformedURLException",
                Toast.LENGTH_SHORT).show();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        dialog.dismiss();
        e.printStackTrace();
        Toast.makeText(UploadToServer.this,
                "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e("Upload file to server Exception",
                "Exception : " + e.getMessage(), e);
    }
    dialog.dismiss();
    return serverResponseCode;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Munez NS
  • 1,011
  • 1
  • 12
  • 31
  • Here it is already answered http://stackoverflow.com/a/25095264/626481 working perfectly – Hanry Feb 24 '16 at 15:12

3 Answers3

2

try this code if you pass required argument to this function it will work 100%.

add $_post["username"],$_post["password"] on php for receiving parameter

public JSONObject getJSONFromUrl(String url, String username,
            String password,  String photo_path) {
InputStream is = null;
    JSONObject jObj = null;
    static String jsonResp = "";
    String CONTENT_TYPE_JSON = "application/json";
    static String json = "";
    Context context;

        try {
            File file = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            if(photo_path != null)
                file = new File(photo_path);

            //add whatever the parameter you need to send along with image
            entity.addPart("username", new StringBody(username));
            entity.addPart("password", new StringBody(password));

            entity.addPart("file", new FileBody(file));
            entity.addPart("filetype",new StringBody("jpeg"));

            httpPost.setEntity(entity);



            HttpResponse httpResponse = httpClient.execute(httpPost);
            int code = httpResponse.getStatusLine().getStatusCode();

            if (code != 200) {
                Log.d("HTTP response code is:", Integer.toString(code));
                return null;
            } else {
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (ConnectTimeoutException e) {



            return null;
        } catch (SocketTimeoutException e) {

            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            jsonResp = sb.toString();



        } catch (Exception e) {

            return null;
        }


        try {
            jObj = new JSONObject(jsonResp);

        } catch (JSONException e) {

        }


        return jObj;
    }
Mugunthan S
  • 538
  • 3
  • 8
  • 21
0

Try the following

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

//...
conn.connect();
zozelfelfo
  • 3,776
  • 2
  • 21
  • 35
0

Use loopj library. It has support for uploading files along with string data. I used it in one of my projects.

fida1989
  • 3,234
  • 1
  • 27
  • 30
  • I would like to go with this library, but I have problems implementing it. If you have a link to a little straight forward example I would appreciate it. As I said, I'm still android noob. This is what I tried, sending only one string param for start: AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("param1", "james"); client.post("http://www.mywebsite.com/web_service/ws_newitem.php", params, null); – Munez NS Aug 27 '14 at 13:01
  • Checkout the samples here: https://github.com/loopj/android-async-http/tree/master/sample – fida1989 Aug 31 '14 at 05:54