Android将Bitmap作为PNG上传到服务器

时间:2016-09-17 01:58:47

标签: java android bitmap

我正在开展一个项目,我需要将图像映射到Bitmap并将其上传到服务器,我无法完全理解它。

这就是我现在正在使用的内容(忽略JSONObject的东西,服务器将其作为响应返回,我还没有构建该部分):

private JSONObject uploadImagesFromMemory(Bitmap bitmap) {
    if (getSelf() == null) {
        try {
            return new JSONObject("");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    HttpURLConnection connection = null;

    try {
        URL url = new URL("REMOVED");
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;");

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(byteArray);

        outputStream.flush();
        outputStream.close();
        connection.disconnect();

        return new JSONObject("{\"responseCode:\"1}");
    } catch (Exception ex) {
        //Exception handling
    }

    return null;
}

我不知道如何将文件的上传名称/变量设置为' toUpload'这是服务器所需要的。

将采取任何建议,谢谢。

3 个答案:

答案 0 :(得分:1)

我改变了我的代码(服务器和客户端)并且它现在正在工作。

服务器只获取Base64数据并将其转换为PNG文件。然后它完成之前所做的事情并保存它:

if (isset($_POST['base64'])) {
$data = $_POST['base64'];
$data = base64_decode($data);

$status = file_put_contents("profiles/$uuid.png", $data);

if ($status == false) {
    echo(json_encode(array(
        "response" => "Failed to change profile picture.",
        "responseCode" => "0"
    )));
} else {
    echo(json_encode(array(
        "response" => "Successfully changed your profile picture!",
        "responseCode" => "1"
    )));
}

}

客户端获取位图,并将其转换为Base64:

public String toBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

然后,使用Volley,上传它:

final ProgressDialog loading = ProgressDialog.show(SettingsActivity.this,"Uploading...","Please wait...",false,false);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, "REMOVED",
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                    //Dismissing the progress dialog
                                    loading.dismiss();
                                    //Showing toast message of the response
                                    try {
                                        JSONObject jsonObject = new JSONObject(s);
                                        int responseCode = Integer.parseInt(jsonObject.getString("responseCode"));
                                        String response = jsonObject.getString("response");
                                        if (responseCode == 1) {
                                            Toast.makeText(SettingsActivity.this, response, Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(SettingsActivity.this, "Error: " + response, Toast.LENGTH_LONG).show();
                                        }
                                    } catch (Exception ex) {
                                        Toast.makeText(SettingsActivity.this, "Failed to upload.", Toast.LENGTH_LONG).show();
                                    }
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    //Dismissing the progress dialog
                                    loading.dismiss();

                                    //Showing toast
                                    try {
                                        JSONObject jsonObject = new JSONObject(volleyError.getMessage());
                                        int responseCode = Integer.parseInt(jsonObject.getString("responseCode"));
                                        String response = jsonObject.getString("response");
                                        if (responseCode == 1) {
                                            Toast.makeText(SettingsActivity.this, response, Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(SettingsActivity.this, "Error: " + response, Toast.LENGTH_LONG).show();
                                        }
                                    } catch (Exception ex) {
                                        Toast.makeText(SettingsActivity.this, "Failed to upload.", Toast.LENGTH_LONG).show();
                                    }
                                }
                            }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            //Converting Bitmap to String
                            String image = Memer.getMemer().toBase64(bitmap);

                            //Getting Image Name

                            //Creating parameters
                            Map<String,String> params = new Hashtable<>();

                            //Adding parameters
                            params.put("base64", image);

                            //returning parameters
                            return params;
                        }
                    };

                    //Creating a Request Queue
                    RequestQueue requestQueue = Volley.newRequestQueue(SettingsActivity.this);

                    //Adding request to the queue
                    requestQueue.add(stringRequest);

希望我能像其他人一样帮助其他人解决这个问题:)

答案 1 :(得分:0)

我发现最简单的方法是使用MultipartEntityBuilder(需要使用apache库)。使用该代码是:

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (Map.Entry<String, File> entry : entities.entrySet())
        {
            builder.addBinaryBody(entry.getKey(), entry.getValue(), ContentType.create("image/jpg"), entry.getValue().getName());
        }
        mMultipartEntity = builder.build();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mMultipartEntity.writeTo(bos);
        }
        catch (IOException ex) {
        }
        return bos.toByteArray();

Android切换到的URLConnection库非常适合简单的查询,但似乎没有相当多的实体支持。

答案 2 :(得分:0)

如果您相应地修改代码,这将有助于您

FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri+"&user_id="+userId);
                // 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("uploaded_file", fileName);

                //conn.setRequestProperty("uname", username);
                //conn.setRequestProperty("uid", userId);
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"edit_pro_pic\";filename=\"" + fileName + "\"" + lineEnd);
                dos.writeBytes(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();
                conn.getResponseMessage();
                s = new Scanner(conn.getInputStream());
                imageUrl = readResponse(s.next());
                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                dialog.dismiss();
                cancel(true);
                ex.printStackTrace();
                //Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {
                dialog.dismiss();
                e.printStackTrace();
                //  Log.e("Upload file to server Exception","Exception : " + e.getMessage(), e);
            }