需要的jar包
1.commons io.jar
2.commons-fileupload.jar
springmvc.xml
image.png
id必须是multipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大上传容积之和 默认字节-->
<property name="maxUploadSize" value="20000000"></property>
<!-- 默认编码方式设置成utf-8 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 最大缓冲大小 -->
<property name="maxInMemorySize" value="2048"></property>
<!-- 懒加载模式 -->
<property name="resolveLazily" value="true"></property>
<!-- 文件上传临时目录,上传完成后,就会将临时文件删除; -->
<property name="uploadTempDir" value=""></property>
<!-- 跟maxUploadSize差不多,不过maxUploadSizePerFile是限制每个上传文件的大小,而maxUploadSize是限制总的上传文件大小 -->
<property name="maxUploadSizePerFile" value=""></property>
<!-- 保存文件名 -->
<property name="preserveFilename" value=""></property>
</bean>
Controller
@PostMapping("upload")
public String upload(MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
if(file.isEmpty())
{
return "upload";
}
else
{
String path = request.getServletContext().getRealPath("/file/");
String filename = file.getOriginalFilename();
File filepath = new File(path,filename);
if(!filepath.getParentFile().exists())
{
filepath.getParentFile().mkdirs();
}
/**
* 获取类型 .*
*/
// String ext = FilenameUtils.getExtension(filename);
/**
* 创建新名字
*/
// String newfileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
String newPath= path+File.separator+filename;
System.out.println("文件路径:"+newPath);
file.transferTo(new File(newPath));
}
return "success";
}
优化下
新建一个模型类 Fileinfo
import java.io.Serializable;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class FileInfo implements Serializable {
private static final long serialVersionUID = 1L;
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
Controller
@PostMapping("upload")
public String upload(@ModelAttribute FileInfo fileInfo,HttpServletRequest request,Model model) throws IllegalStateException, IOException {
if(fileInfo.getFile().isEmpty())
{
return "upload";
}
else
{
String path = request.getServletContext().getRealPath("/file");
String filename = fileInfo.getFile().getOriginalFilename();
File filepath = new File(path,filename);
if(!filepath.getParentFile().exists())
{
filepath.getParentFile().mkdirs();
}
/**
* 获取类型 .*
*/
// String ext = FilenameUtils.getExtension(filename);
/**
* 创建新名字
*/
// String newfileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
String newPath= path+File.separator+filename;
System.out.println("文件路径:"+newPath);
fileInfo.getFile().transferTo(new File(newPath));
model.addAttribute("fileinfo", fileInfo);
}
return "download";
}
前端
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传">
</form>