android - 如何为图像添加唯一名称
问题描述
当我将图像上传到服务器和文件夹以保存它时,我尝试将唯一名称作为数字添加到图像中。我只需要使用数字并且该数字不重复。我寻找了不同的方法来做到这一点,但我没有成功。现在如果我上传图像,名称将与前一个相同,这会使以前的图像从文件夹中删除。如果有人知道解决方案,请帮助我。
我使用这段代码:
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());
简单实用。
推荐阅读
- javascript - JavaScript 中的错误 SQL 查询?
- python - Python:从嵌套的字典列表创建目录树
- c++ - 使用 unsigned int 时的无限循环
- r - 应用 group_by 和 summarise(sum) 但保留大量附加列
- tensorflow - 即使在冻结所有层之后,神经网络也需要时间来训练
- c++ - C++ 使用源代码、静态存档和其他动态库创建动态库
- c# - 在 c# 中列出 SSL 证书(重新创建 IIS 绑定对话框)
- authentication - 使用 Okta 通过 API 访问后端应用程序
- go - 如何在一个会话中发送多个命令但分别保存输出
- ios - iOS Shoutcast 使用 Swift 访问元数据