首页 > 解决方案 > 如何为图像添加唯一名称

问题描述

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

我使用这段代码:




    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);
?> 

标签: android

解决方案


我命名如下

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

简单实用。


推荐阅读