简体   繁体   中英

Parse Server: Remove old profile image associated with a user

I am using File System Storage adapter to save uploaded files on the parse server. In my app each user can have profile photo. when the user wants to change his photo, the old one should be deleted from the server. But the old image remains unchanged. It leads to fill the server storage after some time. Here is my code:

public void update (Uri uri)
    {
        ParseUser user = ParseUser.getCurrentUser();
        if(uri!=null){
            InputStream iStream=getContentResolver().openInputStream(uri);
            byte[]image=Helper.getBytes(iStream);
            ParseFile file=new ParseFile("profile.png",image);
            file.saveInBackground();
            user.put("photo",file);
            user.saveInBackground();
        }
    }

Unfortunately Android SDK does not have a function to delete the file but you can do that using Cloud Code Functions or maybe a trigger. Something like this should solve your problem:

Parse.Cloud.beforeSave('_User', ({ original, object }) => {
  if (original.get('photo').url() !== object.get('photo').url()) {
    original.get('photo').destroy();
  }
});

You should propably delete the line " file.saveInBackground(); ". Because its runs in background. And when you put that file in user object saving file is not complete and parse server will upload same file to server again with the user object. and You will end having two duplicate files.

Change your code to this:

public void update (Uri uri)
    {
        ParseUser user = ParseUser.getCurrentUser();
        if(uri!=null){
            InputStream iStream=getContentResolver().openInputStream(uri);
            byte[]image=Helper.getBytes(iStream);
            ParseFile file=new ParseFile("profile.png",image);
            user.put("photo",file);
            user.saveInBackground();
        }
    }

With this code you upload file only once

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM