springmvc中会自动根据类型封装数据
* list集合封装通过 集合属性名[x].元素属性名 例如:list[0].name
* Map集合封装通过 集合[‘key’].属性即可
-
RequestMapping中:可以使用通配符匹配字符
-
?:匹配文件中一个字符。 *:匹配文件中任意字符。 **:匹配多层路径。
/**
* 重定向和转发关键字:
* redirect:
* forward:
* 使用关键字不会走视图解析器
*/
/**
* 原生servlet上传文件的方式
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/fileUpload")
public String fileUpload(HttpServletRequest request) throws Exception {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(realPath);
//判断uploads文件夹是否存在,如果不存在创建该文件夹
if (!file.exists()) {
file.mkdir();
}
for (FileItem fileItem : fileItems) {
//判断是否是普通的form表单
if (!fileItem.isFormField()) {
String fieldName = fileItem.getName();
System.out.println(fieldName);
String uuid = UUID.randomUUID().toString().replace("-", "");
fieldName = uuid +"_"+fieldName;
//将文件写入到文件夹中
fileItem.write(new File(realPath,fieldName));
//清楚缓存
fileItem.delete();
System.out.println("上传文件成功");
}
}
return "success";
}
使用springmvc的方式上传文件
1.
<!-- 文件解析器 id必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制最大上传文件大小 字节大小 1024*1024*10 10MB-->
<property name="maxUploadSize" value="10485760"></property>
</bean>
<!-- 放行静态资源-->
<mvc:resources mapping="/js/**" location="/js"></mvc:resources>
/**
需要commons-io 和commons-fileupload依赖
* springmvc 为我们提供的上传方式
* MultipartFile 的名字必须与上传文件的名字相同
* @param file2
* @return
*/
@RequestMapping("/fileUpload2")
public String springmvcFileUpload(HttpServletRequest request,MultipartFile file2) throws IOException {
String realPath = request.getSession().getServletContext().getRealPath("/uploads2/");
File file = new File(realPath);
//判断uploads文件夹是否存在,如果不存在创建该文件夹
if (!file.exists()) {
file.mkdir();
}
//获取文件名
String fieldName = file2.getOriginalFilename();
//uuid避免相同文件名
String uuid = UUID.randomUUID().toString().replace("-", "");
//transferTo写入
file2.transferTo(new File(realPath,fieldName));
System.out.println("写入成功");
return "success";
}
跨服务器上传文件
1.导入依赖
<!-- jersey依赖-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
System.out.println("跨服务器文件上传...");
// 定义上传文件服务器路径
String path = "http://localhost:9090/uploads/";
// 说明上传文件项
// 获取上传文件的名称
String filename = file3.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
// 上传文件
webResource.put(file3.getBytes());
return "success";