Not in der Lage, zusätzliche Parameter mit Bild mit HttpURLConnection in Android zu senden

public class UploadProfilePicActivity extends Activity implements View.OnClickListener {
ImageView imageView;
Button btnUploadPic;
Button btnskipUploadPic;
Button btnSaveNContinue;
private static int RESULT_LOAD_IMAGE = 1;
String imagepath = null;
ProgressDialog dialog = null;
String url_profilePic;
private int serverResponseCode;
String api = "http://192.168.2.17:8000/api/v1/";
String format = "/?format=json";
AlmabayDatabase almabayDatabase;
String encodedString;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_uploadprofilepic);
    imageView = (ImageView) findViewById(R.id.imageView);
    btnUploadPic = (Button) findViewById(R.id.btnUploadPic);
    btnskipUploadPic = (Button) findViewById(R.id.btnSkipUploadPic);
    btnSaveNContinue = (Button) findViewById(R.id.btnSaveNContinue);
    btnUploadPic.setOnClickListener(this);
    btnSaveNContinue.setOnClickListener(this);
    url_profilePic = api + "user-media" + format;
    almabayDatabase = new AlmabayDatabase(this);

      }

@Override
public void onClick(View v) {
    if (v == btnUploadPic) {
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

    } else if (v == btnSaveNContinue) {

        dialog = ProgressDialog.show(UploadProfilePicActivity.this, "", "Uploading file...", true);
        //  messageText.setText("uploading started.....");
        new Thread(new Runnable() {
            public void run() {
                Log.e("ImagePathTest", imagepath);

                uploadFile(imagepath);

            }
        }).start();
    }
}



protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
        imageView.setImageBitmap(bitmap);

        Log.e("Uploading", "Uploading File :" + imagepath);
                }
}

public String getPath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}


    public int uploadFile(String imagepath) {

    String fileName = imagepath;
    Log.e("File Name", fileName);

    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(fileName);
    int pk = almabayDatabase.getUserID();

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        ,Log.e("uploadFile", "Source File not exist :" + imagepath);

        runOnUiThread(new Runnable() {
            public void run() {
                                   Log.e("Sourcefile", "File doesn't exist");
            }
        });
        return 0;
    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(url_profilePic);

            // 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("name", fileName);
          //  conn.setRequestProperty("timeline_id", String.valueOf(pk));

            dos = new DataOutputStream(conn.getOutputStream());
            //Send Image
            Log.e("Sending","Sending Image");
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"name\";filename=\"" + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            // add parameter timeline_id
            String timeline_id = String.valueOf(pk);
            Log.e("Sending","Sending PK");
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"timeline_id\"" + lineEnd);
            dos.writeBytes(lineEnd);

            // assign value
            dos.writeBytes(timeline_id);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // create a buffer of  maximum size
            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();
            Log.e("ResponseCode", String.valueOf(serverResponseCode));
            String serverResponseMessage = conn.getResponseMessage();

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

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(UploadProfilePicActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                });
            }

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

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadProfilePicActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    // messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadProfilePicActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file failed", "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

}

In diesem Code versuche ich, ein Bild zusammen mit timeline_id an den Server zu senden. Timeline_id enthält den Wert pk, der der Primärschlüssel des in der Datenbank gespeicherten Benutzers ist. Ich kann kein Bild mit timeline_id senden. Ich weiß nicht, wohin das eigentliche Problem ist.Bitte helfen Sie mir, das Problem zu beheben.

Antworten auf die Frage(6)

Ihre Antwort auf die Frage