问题
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 :
- the user uploads the file which is saved somewhere on the server;
- the user answers the questions associated to the file type;
- 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