【问题标题】:Uploaded files are deleted using Apache Commons FileupLoad and Spring MVC使用 Apache Commons FileupLoad 和 Spring MVC 删除上传的文件
【发布时间】:2013-08-17 06:06:39
【问题描述】:

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

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

感谢您的帮助!

文件上传控制器.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";
}

上传表单.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页面

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

【问题讨论】:

  • 你试过复制而不是移动吗?
  • 我有,但文件仍然被删除。

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


【解决方案1】:

尝试以下将上传的输入流复制到文件的代码。您应该进行更多检查(文件存在,文件已创建......)并将此代码移动到某个帮助程序类。它使用来自 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();
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    如果你使用的是 Spring mvc,你也可以使用这个MultipartFile

    使用您的源代码的示例,

    上传表单.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";
    }
    

    【讨论】: