2

I have been searching this topic for quite a while, and haven't found anything that has been able to solve my problem.. so I turn to you!

I have a JSP where I open a file dialog box to select a file. Previously, I used this to upload the file to a specified directory (in my code). This works fine. I am now trying to use the same code to delete that same file by selecting it in the appropriate directory and passing it off to the servlet, which I included below. I am using the Apache Common FileUpload library to do this.

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        return;
    }

    // configures some settings
    DiskFileItemFactory factory = new DiskFileItemFactory();

    ServletFileUpload delete = new ServletFileUpload(factory);

    // constructs the directory path to delete file
    String deletePath = UPLOAD_DIRECTORY;

    // parses the request's content to extract file data
    List formItems = delete.parseRequest(request);
    Iterator iter = formItems.iterator();

    // iterates over form's fields
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();


        // processes only fields that are not form fields
        if (!item.isFormField()) {


            String fileName = new File(item.getName()).getName();
            String filePath = deletePath + File.separator + fileName;
            File storeFile = new File(filePath);

            //File storeFile = new File("C:\\temp\\discLogo.txt");

            // deletes the file on disk
            boolean erased = storeFile.delete();
            }
        }

UPLOAD_DIRECTORY is where I am storing my files from my upload JSP. The delete method works fine if I uncomment the line I commented out for storeFile with the hardcoded directory, as long as I select a DIFFERENT FILE in the directory initially. This leads me to believe the HttpServletRequest is holding the file in memory somewhere.

Is this correct? is there any way I can release it so I can delete the file I select initially? Or is there a much simpler way to do this?

Thanks!

Joe McG
  • 167
  • 1
  • 2
  • 10

4 Answers4

2

The File#delete() will return false if the file does not exist at all (use File#exists() to test it beforehand), or if the file is locked because it is been opened by another app or even your own code!

Provided that this file is written do disk beforehand by your own code and guaranteed not opened elsewhere, then you should ensure that you're invoking OutputStream#close() in the finally block after writing the file's content. This problem suggests that you didn't. If you leave the file open after writing to it, then it cannot be deleted until you restart the server/JVM.

Apache Commons IO, which you should already have as a dependency of FileUpload, comes with handy utility methods reducing the file copy and close boilerplate.

InputStream input = item.getInputStream();
OutputStream output = new FileOutputStream(storeFile);

try {
    IOUtils.copy(input, output);
} finally {
    IOUtils.closeQuietly(output);
    IOUtils.closeQuietly(input);
}

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

What is the object of uploading the file? Are you going to check all the files by content?

I would say the simpler way would be to not upload the whole file. What you want to do is to call some code - JSP/Servlet -, pass as a parameter an ID of the file (most usually the path inside the server) and make it delete the file. If all the files uploaded are in the same folder, then the name should be enough (*).

After all, by uploading the file you are forcing you to have a copy in your PC of the file you want to delete (what if you deleted your local file? Should you not be able to delete the file in the server?)

(*) be sure to perform safety checks so nobody can pass ..\..\WEB-INF\web.xml as a parameter.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • Thanks for your reply! I agree... it would be simpler to just bring in the name of the file I am selecting, creating the file name, and then deleting it. How do I grab this (just the file name) from the HttpServletRequest? I have looked at getLocalName(), getContextPath(), getPathInfo(), getPathTranslated()... none seem to return what I am looking for. Forgive my ignorance on the matter, I am pretty new at this. – Joe McG Jan 18 '13 at 00:09
  • No, no, no. Forget about files. It is as simple as an HTML `select` listing all the paths available for deleting. Just use "regular" HTTP request parameters. – SJuan76 Jan 18 '13 at 00:18
  • this will list all the files, though won't it? I want to be able to individually select a file on the JSP through a fileChooser, pass that off to a Servlet, and have the Servlet delete the file. – Joe McG Jan 18 '13 at 00:21
1

you can delete the file because the platform indepenedent solution is like this

File deleteFile = new File(<file Path> ) ;
// check if the file  present or not
if( deleteFile.exists() )
deleteFile.delete() ;

Be carefule if the file path is directory then the directory must empty before deleting. UploadFileorDelete

Sheel
  • 847
  • 2
  • 8
  • 20
0

Looks like my issue was in my JSP. I had the following form initially:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Delete</title>
</head>
<body>
    <form method="post" action="DeleteServlet"
        enctype="multipart/form-data">
        Select file to delete: <input type="file" name="dataFile"
            id="fileChooser" /><br />
        <br /> <input type="submit" value="Delete" />
    </form>
</body>
</html>

I changed this by deleting encytype="multipart/form-data" from the form, and was then able to use request.getParameter("dataFile") to get the file name.

Joe McG
  • 167
  • 1
  • 2
  • 10
  • This is not the right solution. You should in the server side not be interested in the file name, but in the file content. The code as you've so far would only work in an environment where both the webbrowser and the webserver happen to run at physically the same machine (because they would have access to the same local disk file system). This does absolutely not occur in real world at all and is exactly the reason why Apache Commons FileUpload exist. See also http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3/3374408#3374408 – BalusC Feb 04 '13 at 20:55