Java Servlet 3.0 File Upload - Removing TMP Files

落爺英雄遲暮 提交于 2020-05-13 19:13:07

问题


I'm using the Java Servlet 3.0 to upload files, using the @MultipartConfig annotation and request.getParts() to obtain the files.

When a file is uploaded, a TMP file is created in the Web Application work directory (tomcat/work/Catalina/localhost/webappname). For example:

upload_7c59101b_9f97_4e3f_9fa5_e484056d26fa_00000209.tmp

The application copies the file to another directory on the server - I'm doing this using the part.write() method but it's also working by obtaining the input stream and writing the bytes. Either way works fine.

I need to remove the TMP files after the upload, but I'm having trouble doing so. The part.delete() method doesn't do anything. I've also tried accessing the files in the directory using javax.servlet.context.tempdir and iterating over them to delete, but when calling a delete method, it always returns false. Using the Files.delete(path) method from Files.nio returns an exception which claims the file is in use by another program (i.e. locked) and therefore cannot be deleted. The server is running Windows Server 2012 R2.

Does anyone have any other solutions to remove these TMP files? It's worth pointing out that I've tried using a HttpRequestListener too, but still cannot delete the files.

Many thanks


回答1:


You should (must!) not manipulate the files directly, you should use the getInputStream() method of the particular Part to get the content of the uploaded file. The servlet container (Tomcat in your case) will - or at least should - take care of the temporary files.




回答2:


Along with InputStream.close(), use Part.delete() to remove the stored temporary file under work directory. Please refer the javadoc: Part.delete().




回答3:


I agree with Jozef Chocholacek answer, simple solution CLOSE the input. We were using MultiPart messages with files upload. Since we were not closing the inputStream the files were stored there for a loooong time. They were deleted only on server restart.

After slightly changing the implementation with always closing the input part at the end.

Use try-> catch-> finally and put closing in finally part which will be called always even when the call of method fails.

The server is not storing .tmp files anymore.



来源:https://stackoverflow.com/questions/31741477/java-servlet-3-0-file-upload-removing-tmp-files

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