如何为图像安卓添加唯一名称



当我将图像上传到服务器和文件夹以保存它时,我尝试将唯一名称作为数字添加到图像中。 我只需要使用数字,而该数字不重复。我寻找不同的方法来做到这一点,但我没有成功。现在,如果我上传图像,名称将与上一个图像相同,这使得上一个图像从文件夹中删除。 如果有人知道解决方案,请帮助我。

我使用此代码:



private void upload() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, upload_url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
Toast.makeText(Add.this, Response, Toast.LENGTH_LONG).show();

} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (bitmap != null)
{
params.put("image", imageToString(bitmap));
params.put("webformatURL", img_location + "/" + textfrom.getText().toString().trim() + ".jpg");
}
params.put("FROM", textfrom.getText().toString().trim());

return params;
}
};
RequestQueue requestQueue = (RequestQueue) Volley.newRequestQueue(Add.this);
requestQueue.add(stringRequest);

}


和 PHP 文件


<?php
$servername = "localhost";
$username = "localhost";
$password = "localhost";
$dbname = "localhost";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($conn) {

$image = $_POST["image"];
$webformatURL = $_POST["webformatURL"];
$FROM = $_POST["FROM"];
$date = date('Y-m-d');

$sql = "insert into image(FROM,webformatURL) values('$FROM','$webformatURL')";
$upload_path = "uploads/$FROM.jpg";
if(mysqli_query($conn, $sql))
{
file_put_contents($upload_path, base64_decode($image));
echo json_encode(array('response' => 'Image Upload Successfully'));
} else {
echo json_encode(array('response' => 'Image Upload Failed'));
}
} else {
echo json_encode(array('response' => 'Connection Error'));
}
mysqli_close($conn);
?> 

我像下面这样命名

String fileName = String.format(Locale.US, "%d.jpg", System.currentTimeMillis());

简单实用。

最新更新