【问题标题】:Android - Firebase rename file(SHA-1) before uploadAndroid - 上传前的 Firebase 重命名文件(SHA-1)
【发布时间】:2017-11-13 06:23:56
【问题描述】:

大家,我需要在上传到 Firebase 存储之前重命名文件 将多张图片上传并编码到 sha-1 (imagename + uid + current time):

915731b2094b1cb23c1b176ef8633947f737804b,fdf15718d6d988ce188bdc8debcb7d5998229db3

我从这个链接获得的多选图片https://github.com/donglua/PhotoPicker

主板发布类(发布到 Firebase 存储并标记到 Firebase 数据库的类,但现在我不必将 sha1hash 放入 Firebase 数据库

   private static final String TAG = "MainboardPost";
private static final int MAP_REQUEST_CODE = 334;
private static final int ADD_PHOTO_REQUEST = 335;
private Toolbar toolbar;
private TextView cancle;
private Mainboard post;
private PhotoAdapter photoAdapter;
private ArrayList<String> selectedPhotos = new ArrayList<>();
Button img_btn,map_btn,removeMapBtn;
RelativeLayout layout_img , layout_map ;
private RecyclerView recyclerView;
EditText header , body;

private UploadTask mUploadtask;

ImageButton addMapBtn;
FrameLayout frameLayout;

private FirebaseStorage storageRef;
private StorageReference mStorage , folderRef;
private DatabaseReference mDatabase;

// รับค่าlat lon เพื่อโพส
private String loc_latlon;
private String loc_address;

private FirebaseAuth mAuth;

GoogleMap map;
Marker mMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_mainbard_post);
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
    setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar


    mAuth = FirebaseAuth.getInstance();

    mDatabase = FirebaseDatabase.getInstance().getReference();

    storageRef = FirebaseStorage.getInstance();
    mStorage = storageRef.getReference();
    folderRef = mStorage.child("mainboard");


    frameLayout = (FrameLayout)findViewById(R.id.map_frame);
    removeMapBtn = (Button)findViewById(R.id.remove_btn);
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
    header = (EditText)findViewById(R.id.topic);
    body = (EditText)findViewById(R.id.detail);
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);

    img_btn = (Button)findViewById(R.id.add_img);
    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_img.setVisibility(View.VISIBLE);
            layout_map.setVisibility(View.GONE);
        }
    });
    map_btn = (Button)findViewById(R.id.add_map);
    map_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_map.setVisibility(View.VISIBLE);
            layout_img.setVisibility(View.GONE);

        }
    });

    cancle = (TextView) findViewById(R.id.toolbar_cancle);
    cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });


    addMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
            startActivityForResult(intent, MAP_REQUEST_CODE);
        }
    });

    removeMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            frameLayout.setVisibility(View.GONE);
            addMapBtn.setVisibility(View.VISIBLE);
        }
    });

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
    recyclerView.setAdapter(photoAdapter);

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
            new RecyclerItemClick.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                        PhotoPicker.builder()
                                .setPhotoCount(PhotoAdapter.MAX)
                                .setShowCamera(true)
                                .setPreviewEnabled(false)
                                .setSelected(selectedPhotos)
                                .start(MainboardPost.this, REQUEST_CODE);
                    } else {
                        PhotoPreview.builder()
                                .setPhotos(selectedPhotos)
                                .setCurrentItem(position)
                                .start(MainboardPost.this, REQUEST_CODE);
                    }
                }
            }));

    setUpGoogleMap();

}

//Menu Item ขวามือสุดของ Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_post, menu);
    return true;
}

private void setUpGoogleMap() {
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {

        SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
        map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MAP_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                //Location Fetched
                double lat = data.getDoubleExtra("location_lat", 0);
                double lng = data.getDoubleExtra("location_lng", 0);

                loc_latlon = lat + "," + lng;

                Log.e("Selected Lat-lng", lat + " - " + lng);
                frameLayout.setVisibility(View.VISIBLE);
                addMapBtn.setVisibility(View.GONE);
                //Here after getting lat lng add marker to ur google map using fetched lat lng
                setPickedLocationOverMap(lat, lng);
                //
            }
            break;
        case REQUEST_CODE:
            if (resultCode == RESULT_OK &&
                    (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
            break;
    }
}

private void setPickedLocationOverMap(double lat, double lng) {
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this.getApplicationContext());
    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
    if (map != null)
        map.animateCamera(cameraUpdate);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    submitPost();
    return true;
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button_upload_resume:
            Helper.mProgressDialog.show();
            mUploadtask.resume();
            break;
    }
}

private void submitPost() {


    final String title = header.getText().toString().trim();
    final String detail = body.getText().toString().trim();

    if (loc_latlon == null){
        loc_latlon = "";
    }

    if (loc_address == null){
        loc_address = "";
    }

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){
        final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user == null){
                    Log.e(TAG, "User " + userId + " is unexpectedly null");
                    Toast.makeText(MainboardPost.this,
                            "Error: could not fetch user.",
                            Toast.LENGTH_SHORT).show();

                }else {
                    writenewpost(title , detail , loc_latlon , loc_address);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            }
        });
    }
    for (String imagePath : selectedPhotos){
        Uri file =  Uri.fromFile(new File(imagePath));
        StorageReference imageRef = folderRef.child(file.getLastPathSegment());
        mUploadtask = imageRef.putFile(file);

    }

}

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )

{

    String key = mDatabase.child("mainboard").push().getKey();
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);

    Map<String, Object>postvalue = mainboard_post.toMap();
    Map<String, Object>childUpdates = new HashMap<>();
    childUpdates.put("/mainboard/" + key , postvalue);

    mDatabase.updateChildren(childUpdates);
}

主板立柱模型

public String mb_address;
public String mb_body;
public String mb_location;
public String mb_pic;
public String mb_title ;

public PostMainboard(){

}

public PostMainboard( String mb_title ,String mb_body,String mb_location,String mb_address , String mb_pic)

{
    this.mb_address = mb_address;
    this.mb_body = mb_body;
    this.mb_location = mb_location;
    this.mb_pic = mb_pic;
    this.mb_title = mb_title;
}

@Exclude
public Map<String , Object> toMap(){
    HashMap<String, Object> result = new HashMap<>();
    result.put("mb_title" , mb_title);
    result.put("mb_body" , mb_body);
    result.put("mb_location" , mb_location);
    result.put("mb_address" , mb_address);
    result.put("mb_pic" , mb_pic);
    return result;
}

}

【问题讨论】:

    标签: android firebase encryption firebase-realtime-database firebase-storage


    【解决方案1】:

    以下是用于创建 SHA-1 证书的支持类。这可能对你有帮助。

    1.创建一个名为SHA1Hash.javaclass 并粘贴以下代码。导入必要的包。

    public class SHA1Hash {
    
        private static String convertToHex(byte[] data) {
            StringBuilder buf = new StringBuilder();
            for (byte b : data) {
                int halfbyte = (b >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                    halfbyte = b & 0x0F;
                } while (two_halfs++ < 1);
            }
            return buf.toString();
        }
    
        public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            byte[] sha1hash = md.digest();
            return convertToHex(sha1hash);
        }
    }
    

    2。使用如下调用方法使用 datetime 和您必要的 String 值创建 SHA1 证书。

            public static String getDateTimeHash(String uid, String imageName){
                final String HASH_KEY = uid+imageName;
                String hashString = "";
                String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
                try {
                   hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Log.d("Utils","Hash Value is "+hashString);
                return  hashString ; 
            }
    

    根据您的需要编辑了使用方法。您可以将imageName+uid+currentTime 作为String 传递,因为该方法采用String 类型的值

    你的最终代码:

    private static final String TAG = "MainboardPost";
    private static final int MAP_REQUEST_CODE = 334;
    private static final int ADD_PHOTO_REQUEST = 335;
    private Toolbar toolbar;
    private TextView cancle;
    private Mainboard post;
    private PhotoAdapter photoAdapter;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    Button img_btn,map_btn,removeMapBtn;
    RelativeLayout layout_img , layout_map ;
    private RecyclerView recyclerView;
    EditText header , body;
    
    private UploadTask mUploadtask;
    
    ImageButton addMapBtn;
    FrameLayout frameLayout;
    
    private FirebaseStorage storageRef;
    private StorageReference mStorage , folderRef;
    private DatabaseReference mDatabase;
    
    // รับค่าlat lon เพื่อโพส
    private String loc_latlon;
    private String loc_address;
    
    private FirebaseAuth mAuth;
    
    GoogleMap map;
    Marker mMarker;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_mainbard_post);
        toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
        setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
        getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar
    
    
        mAuth = FirebaseAuth.getInstance();
    
        mDatabase = FirebaseDatabase.getInstance().getReference();
    
        storageRef = FirebaseStorage.getInstance();
        mStorage = storageRef.getReference();
        folderRef = mStorage.child("mainboard");
    
    
        frameLayout = (FrameLayout)findViewById(R.id.map_frame);
        removeMapBtn = (Button)findViewById(R.id.remove_btn);
        addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
        layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
        layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
        recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
        header = (EditText)findViewById(R.id.topic);
        body = (EditText)findViewById(R.id.detail);
        photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);
    
        img_btn = (Button)findViewById(R.id.add_img);
        img_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                layout_img.setVisibility(View.VISIBLE);
                layout_map.setVisibility(View.GONE);
            }
        });
        map_btn = (Button)findViewById(R.id.add_map);
        map_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                layout_map.setVisibility(View.VISIBLE);
                layout_img.setVisibility(View.GONE);
    
            }
        });
    
        cancle = (TextView) findViewById(R.id.toolbar_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    
    
        addMapBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
                startActivityForResult(intent, MAP_REQUEST_CODE);
            }
        });
    
        removeMapBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                frameLayout.setVisibility(View.GONE);
                addMapBtn.setVisibility(View.VISIBLE);
            }
        });
    
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        recyclerView.setAdapter(photoAdapter);
    
        recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
                new RecyclerItemClick.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(PhotoAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(selectedPhotos)
                                    .start(MainboardPost.this, REQUEST_CODE);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(MainboardPost.this, REQUEST_CODE);
                        }
                    }
                }));
    
        setUpGoogleMap();
    
    }
    
    //Menu Item ขวามือสุดของ Toolbar
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_post, menu);
        return true;
    }
    
    private void setUpGoogleMap() {
        if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {
    
            SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
            map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case MAP_REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    //Location Fetched
                    double lat = data.getDoubleExtra("location_lat", 0);
                    double lng = data.getDoubleExtra("location_lng", 0);
    
                    loc_latlon = lat + "," + lng;
    
                    Log.e("Selected Lat-lng", lat + " - " + lng);
                    frameLayout.setVisibility(View.VISIBLE);
                    addMapBtn.setVisibility(View.GONE);
                    //Here after getting lat lng add marker to ur google map using fetched lat lng
                    setPickedLocationOverMap(lat, lng);
                    //
                }
                break;
            case REQUEST_CODE:
                if (resultCode == RESULT_OK &&
                        (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                    List<String> photos = null;
                    if (data != null) {
                        photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    }
                    selectedPhotos.clear();
    
                    if (photos != null) {
    
                        selectedPhotos.addAll(photos);
                    }
                    photoAdapter.notifyDataSetChanged();
                }
                break;
        }
    }
    
    private void setPickedLocationOverMap(double lat, double lng) {
        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        MapsInitializer.initialize(this.getApplicationContext());
        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
        if (map != null)
            map.animateCamera(cameraUpdate);
    
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.map = googleMap;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        submitPost();
        return true;
    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button_upload_resume:
                Helper.mProgressDialog.show();
                mUploadtask.resume();
                break;
        }
    }
    
    private void submitPost() {
    
    
        final String title = header.getText().toString().trim();
        final String detail = body.getText().toString().trim();
    final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
    
        if (loc_latlon == null){
            loc_latlon = "";
        }
    
        if (loc_address == null){
            loc_address = "";
        }
    
        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){
    
            mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user = dataSnapshot.getValue(User.class);
                    if (user == null){
                        Log.e(TAG, "User " + userId + " is unexpectedly null");
                        Toast.makeText(MainboardPost.this,
                                "Error: could not fetch user.",
                                Toast.LENGTH_SHORT).show();
    
                    }else {
                        writenewpost(title , detail , loc_latlon , loc_address);
    
                    }
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                }
            });
        }
        for (String imagePath : selectedPhotos){
            Uri file =  Uri.fromFile(new File(imagePath));
             String imageName=imagePath.substring(imagePath.lastIndexOf("/")+1);
             Log.d("ImageName" , imageName) ; 
             String hashImageName = getDateTimeHash(userId, imageName); 
             Log.d("HashImageName" , hashImageName); 
            StorageReference imageRef = folderRef.child(hashImageName);
            mUploadtask = imageRef.putFile(file);
    
        }
    
    }
    
    private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )
    
    {
    
        String key = mDatabase.child("mainboard").push().getKey();
        PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);
    
        Map<String, Object>postvalue = mainboard_post.toMap();
        Map<String, Object>childUpdates = new HashMap<>();
        childUpdates.put("/mainboard/" + key , postvalue);
    
        mDatabase.updateChildren(childUpdates);
    }
    
    public static String getDateTimeHash(String uid, String imageName){
                final String HASH_KEY = uid+imageName;
                String hashString = "";
                String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
                try {
                   hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Log.d("Utils","Hash Value is "+hashString);
                return  hashString ; 
            }
    

    希望这对您有所帮助。谢谢

    【讨论】:

    • 感谢您的回复,但我是新手,为此我创建了类以及如何在我的代码中使用
    • 好的,让我检查您的代码并为您获取 imageName 和 uid。 @C.Junior 我在哪里可以得到你班上的 imageName 和 uid。
    • 我编辑了函数参数,现在只需通过传递您的 uid 和 imageName 来使用此方法,它将返回一个 sha1 键作为字符串。您可以在任何您想要的课程或活动中使用此功能。
    • C.Junior 你能用这个解决方案吗?如果您遇到任何问题,请告诉我。
    • 对不起先生,我会更新我的代码有问题和文件名我找不到它我认为使用与手机图像名称相同
    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2017-05-19
    • 2016-09-21
    • 2016-07-13
    相关资源
    最近更新 更多