我是 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>