我改變了我的代碼相當多的(服務器和客戶端)和它的工作現在。
服務器僅取得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);
}
然後,用排槍,它上傳它:
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);
希望我能幫助其他人像我這樣的問題奮鬥:)