使用Apache Commons FileupLoad和Spring MVC删除上传的文件

时间:2013-08-15 04:00:47

标签: java-ee spring-mvc apache-commons-fileupload

我是Spring新手,我想使用Apache Commons FileUpload库。上传有效,但最终删除了上传的文件。我查看了FileUpload文档,并指出一旦文件不再被引用,它将被垃圾收集。

我有一个用于处理上传的控制器。我尝试将文件上传到我在上下文根目录mywebapp \ temp下创建的临时目录。文件上传后,最终会被删除。上传后,我尝试将其移动到另一个目录,mywebapp \ upload \ images。该文件仍然被删除。我不确定我做错了什么。

感谢您的帮助!

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>

2 个答案:

答案 0 :(得分:0)

尝试以下将上传的输入流复制到文件的代码。您应该进行更多检查(文件存在,文件创建...)并将此代码移动到某个帮助程序类。它使用来自commons-io库的org.apache.commons.io.IOUtils

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();
            }
        }
    }
}

答案 1 :(得分:0)

如果您使用的是Spring mvc,也可以使用此MultipartFile

使用您的来源的示例

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";
}