1. 传统方式的文件上传
传统方式的文件上传,指的是我们上传的文件和访问的应用存在于同一台服务器上,并且上传完成之后,浏览器可能跳转。
编写文件上传页面:
<form action="/fileUpload" method="post" enctype="multipart/form-data">
名称: <input type="text" name="picname"/><br/>
图片: <input type="file" name="uploadFile"/><br/>
<input type="submit" value="上传"/>
</form>
编写控制器:
@Controller
public class FileUploadController {
@RequestMapping("/fileUpload")
public String testResponseJson(String picname, MultipartFile uploadFile, HttpServletRequest request) throws Exception{
//1.定义文件名
String fileName = "";
//获取原始文件名
String uploadFileName = uploadFile.getOriginalFilename();
//截取文件扩展名
String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1, uploadFileName.length());
//把文件加上随机数,防止文件重复
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//判断是否输入了文件名
if(!StringUtils.isEmpty(picname)) {
fileName = uuid + "_" + picname + "." + extendName;
}else {
fileName = uuid + "_" + uploadFileName;
}
//2.获取文件路径
ServletContext context = request.getServletContext();
String basePath = context.getRealPath("/uploads");
//解决同一文件夹中文件过多问题
String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//判断路径是否存在
File file = new File(basePath + "/" + datePath);
if(!file.exists()) {
file.mkdirs();
}
//3.使用 MulitpartFile接口中方法,把上传的文件写到指定位置
uploadFile.transferTo(new File(file, fileName));
return "success";
}
}
配置文件解析器:
<!-- 配置文件上传解析器 -->
<!-- bean的 id是固定的-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
注意:文件上传的解析器bean的id是固定的,不能起别的名称,否则无法实现请求参数的绑定。
2. 跨服务器方式的文件上传
在实际开发中,我们会有很多处理不同功能的服务器,例如:应用服务器(负责部署我们的应用),数据库服务器(运行我们的数据库),缓存和消息服务器(负责处理大并发访问的缓存和消息),文件服务器(负责存储用户上传文件的服务器)。
@Controller("fileUploadController2")
public class FileUploadController2 {
public static final String FILESERVERURL = "http://localhost:9090/image_serve/uploads/";
@RequestMapping("/fileUpload2")
public String testResponseJson(String picname,MultipartFile uploadFile) throws Exception{
//1.定义文件名
String fileName = "";
//获取原始文件名
String uploadFileName = uploadFile.getOriginalFilename();
//截取文件扩展名
String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1, uploadFileName.length());
//把文件加上随机数,防止文件重复
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//判断是否输入了文件名
if(!StringUtils.isEmpty(picname)) {
fileName = uuid + "_" + picname + "." + extendName;
}else {
fileName = uuid + "_" + uploadFileName;
}
//2.创建 sun公司提供的 jersey包中的 Client对象
Client client = Client.create();
//指定上传文件的地址,该地址是 web路径
WebResource resource = client.resource(FILESERVERURL + fileName);
//3.实现上传
resource.put(String.class, uploadFile.getBytes());
return "success";
}
}