Pergunta

I am new to Spring, and I want to use the Apache Commons FileUpload library. The upload works, but the uploaded file eventually is deleted. I looked at the FileUpload documentation, and it states that once the file is no longer being referenced, it will be garbage collected.

I have a controller that I use to process the upload. I tried uploading the file to a temp directory I created under the context root, mywebapp\temp. Once the file is uploaded it eventually gets deleted. I tried moving it to another directory after it was uploaded, mywebapp\upload\images. The file still gets deleted. I'm not sure what I am doing wrong.

Thanks for any help!

FileUploadController.java

@RequestMapping(value="uploadFile.request", method=RequestMethod.POST)
protected String uploadFile {@ModelAttribute("uploadForm")UploadForm uploadForm, BindingResult result
    if(!result.hasErrors()) {
        CommonsMultipartFile multipartFile = uploadForm.getMultipartFile();

        // Make sure the file has content.
        if(multipartFile != null && multipartFile.getSize() > 0) {
            FileItem item = multipartFile.getFileItem();

            // Absolute file path to the temp directory
            String tempDirectoryPath = context.getInitParameter("TempDirectoryPath");
            // Absolute file path to the upload directory
            String uploadDirectoryPath = context.getInitParameter("UploadDirectoryPath");

            // Upload to temp directory
            File uploadFile = new File(tempDirectoryPath + File.separator + fileName);
            fileItem.write(uploadFile);

            // Move the file to its final destination
            FileUtils.moveFileToDirectory(uploadFile, new File(uploadDirectoryPath), true);

        }
    return "nextPage";
}

UploadForm.java

import org.apache.commons.fileupload.FileItem;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadForm {
    private String name = null;
    private CommonsMultipartFile multipartFile;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public CommonsMultipartFile getMultipartFile() {
        return multipartFile;
    }
    public void setMultipartFile(CommonsMultipartFile multipartFile) {
        this.multipartFile = multipartFile;
        this.name = multipartFile.getOriginalFilename();
   }

}

springConfig.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="3145728"/>
</bean>

jsp page

<form:form action="uploadFile.request" method="POST" modelAttribute="uploadForm">
    <form:input path="mulitipartFile" type="file"/>
    <input type="submit" value="Upload File"/>
</form>
Foi útil?

Solução

Try following code that copy uploaded input stream to file. You should make more checks (file exists, file created ...) and move this code to some helper class maybe. It uses org.apache.commons.io.IOUtils from commons-io library.

if(multipartFile != null && multipartFile.getSize() > 0) {
    // Upload to temp directory
    File uploadFile = new File("/tmp/" + multipartFile.getOriginalFilename());
    FileOutputStream fos = null;
    try {
        uploadFile.createNewFile();
        fos = new FileOutputStream(uploadFile);
        IOUtils.copy(multipartFile.getInputStream(), fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Outras dicas

If you are using Spring mvc you can use this MultipartFile also.

An example using your source,

UploadForm.java

import org.springframework.web.multipart.MultipartFile;

public class UploadForm {
    private MultipartFile multipartFile;

    public MultipartFile getMultipartFile() {
        return multipartFile;
    }
    public void setMultipartFile(MultipartFile multipartFile) {
        this.multipartFile = multipartFile;
   }

}


@RequestMapping(value="uploadFile.request", method=RequestMethod.POST)
protected String uploadFile {@ModelAttribute("uploadForm")UploadForm uploadForm, BindingResult result
    if(!result.hasErrors()) {
        MultipartFile multipartFile = uploadForm.getMultipartFile();

        // Is Existing on request?
        if (multipartFile == null) {
            throw new RuntimeException("The file is not existing.");
        }
        // Is file empty?
        if (multipartFile.isEmpty()) {
            throw new RuntimeException("File has no content.");
        }
        // Is it of selected type?
        if (!FilenameUtils.isExtension(multipartFile.getOriginalFilename(), new String[]{"doc", "docx"})) {
            throw new RuntimeException("File has a not accepted type.");
        }

        // Absolute file path to the temp directory
        String tempDirectoryPath = context.getInitParameter("TempDirectoryPath");
        // Absolute file path to the upload directory
        String uploadDirectoryPath = context.getInitParameter("UploadDirectoryPath");

        // Upload to temp directory
        File uploadFile = new File(tempDirectoryPath + File.separator + fileName);
        multipartFile.transferTo(uploadFile); // <= Transfer content method!!

        // Move the file to its final destination
        FileUtils.moveFileToDirectory(uploadFile, new File(uploadDirectoryPath), true);

    return "nextPage";
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top