文章目录
1.导入文件上传所需要的jar包
2. 配置文件解析器
3.写一个前端页面
4.写后台程序
1.导入文件上传所需要的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2. 配置文件解析器
<!--文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxInMemorySize" value="10485760"/>
</bean>
3.写一个前端页面
<form action="/user/fileUpload" method="post"
enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br>
<input type="submit" value="上传"/>
</form>
4.写后台程序
@Controller
@RequestMapping("/user")
public class FileUploadController {
@RequestMapping("/fileUpload")
public String fileUpload(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("文件上传");
//使用fileUpload组件完成文件上传
//上传的位置
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
//判断该路径是否存在
File file = new File(realPath);
if(!file.exists()){
//创建该文件
file.mkdirs();
}
//获取到上传文件的名称
String fileName = upload.getOriginalFilename();
//防止文件上传被覆盖,将文件名设置为唯一的
String uuid= UUID.randomUUID().toString().replace("-","");
fileName = uuid+"_"+fileName;
//完成文件上传
upload.transferTo(new File(realPath,fileName));
return "success";
}
}