ndroid中的HttpURLConnection发送带有图像的

ndroid中的HttpURLConnection发送带有图像的

本文介绍了无法使用android中的HttpURLConnection发送带有图像的其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
}

}

在这段代码中,我试图将图像与timeline_id一起发送到服务器.timeline_id包含值pk,该值是存储在数据库中的用户的主键.我无法使用timeline_id发送图像.知道实际问题在哪里.请帮助我解决问题.

In this code ,I am trying to send image to server alongwith timeline_id .timeline_id contains the value pk that is the primary key of the user stored in the database.I am not able to send image with timeline_id.I don't know where the actual problem is.Please help me to resolve the issue.

推荐答案

您可以使用下面的类简单地将文件部分和文本部分放在一起.

You can simple put the file part along with the text part using the class below.

 String charset = "UTF-8";
 String requestURL = BASE_URL + "userregistration";

      MultipartUtility multipart = new MultipartUtility(requestURL, charset);
      multipart.addFormField("username", userJid);
      multipart.addFilePart("image", imageBitmap);//ima
      String response = multipart.finish();
      Log.d("SERVER REPLIED", response);

您可以按照以下步骤创建MultipartUtility类-

You can create an MultipartUtility class as follow-

public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("api_key", "a05f9ece-cd34-11e4-afdc-1681e6b88ec1");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--").
                append(boundary).
                append(LINE_FEED).
                append("Content-Disposition: form-data; name=\"").
                append(name).append("\"").
                append(LINE_FEED).
                append("Content-Type: text/plain; charset=").
                append(charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param fileBytes a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, byte[] fileBytes)
            throws IOException {
//        String fileName = uploadFile.getName();
        writer.append("--")
                .append(boundary)
                .append(LINE_FEED)
                .append("Content-Disposition: form-data; name=\"")
                .append(fieldName)
                .append("\"; filename=\"")
                .append("user.jpeg")
                .append("\"")
                .append(LINE_FEED)
                .append("Content-Type: image/jpeg")
                .append(LINE_FEED)
                .append("Content-Transfer-Encoding: binary")
                .append(LINE_FEED)
                .append(LINE_FEED);
        writer.flush();

        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name).append(": ").append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */

    public String finish() throws IOException {
        writer.append(LINE_FEED).flush();
        writer.append("--")
                .append(boundary)
                .append("--")
                .append(LINE_FEED)
                .close();
        String data = "";
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                data = data + line;
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
        return data.isEmpty() ? null : data;
    }
}

这篇关于无法使用android中的HttpURLConnection发送带有图像的其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 18:20