How to handle and delete “forgotten” uploaded files?

三世轮回 提交于 2019-12-29 01:57:08

问题


I have a form to upload different kind of files. I need to ask questions according to the uploaded file type. For instance, if the file is a pdf, I need to ask the author. If the file is an mp3, I need to ask the title of the song.

So :

  1. the user uploads the file which is saved somewhere on the server;
  2. the user answers the questions associated to the file type;
  3. the user clicks the Save button (the answers are validated) to confirm everything.

Everything is fine so far. Now what if the user never answer the questions or never click the Save Button? Obviously I need to delete this "forgotten" file.

An idea I had was to store "unconfirmed" files in a kind of remote buffer cleaned on a regular basis. Problem is managing appropriately this buffer and deciding when to clean it.

Is there any best practice / existing solution for this? What is the best approach?


回答1:


Keep track of those unconfirmed uploaded files in a @SessionScoped bean and use @PreDestroy to perform cleanup.

Kickoff example:

@SessionScoped
public class UserFileManager {

    private List<File> unconfirmedUploadedFiles;

    @PostConstruct
    public void init() {
        unconfirmedUploadedFiles = new ArrayList<>();
    }

    public void addUnconfirmedUploadedFile(File unconfirmedUploadedFile) {
        unconfirmedUploadedFiles.add(unconfirmedUploadedFile);
    }

    public void confirmUploadedFile(File confirmedUploadedFile) {
        unconfirmedUploadedFiles.remove(confirmedUploadedFile);
    }

    @PreDestroy
    public void destroy() {
        for (File unconfirmedUploadedFile : unconfirmedUploadedFiles) {
            unconfirmedUploadedFile.delete();
        }
    }

}

Do note that you shouldn't be storing the file content in server's memory. It will blow up the server sooner or later. Rather store them on disk and pass around File references.



来源:https://stackoverflow.com/questions/27833140/how-to-handle-and-delete-forgotten-uploaded-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!