黑马程序员技术交流社区
标题: 【广州校区】基于springMVC的文件上传 [打印本页]
作者: Mylo 时间: 2018-12-13 15:29
标题: 【广州校区】基于springMVC的文件上传
1.页面
<form action="/upload" method="post" enctype="multipart/form-data">
用户:<input type="text" name="username"> <br>
文件:<input type="file" name="imgFile"> <br>
<input type="submit" value="上传">
</form>
注意:使用post的提交方式 method="post" enctype="multipart/form-data"
<input type="file" name="imgFile">
2.web.xml
<!--SpringMVC核心控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.springMVC.xml
<!--开启注解扫描-->
<context:component-scan base-package="test.mylo"></context:component-scan>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--跳转的文件的目录:http://localhost:8080/pages/-->
<property name="prefix" value="/pages/"></property>
<!--文件的后缀:http://localhost:8080/pages/success.jsp-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--开启SpringMVC的注解支持-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--文件上传解析器-->
<!--id 必须指定固定名称,否则解析会失败。-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>
4.java 类
@RequestMapping("upload")
public String fileUpload(String username,HttpServletRequest request,
MultipartFile imgFile) throws Exception {
System.out.println("输入用户名:" + username);
//1. 获取上传文件路径
String path = request.getSession().getServletContext().getRealPath("/upload/");
//2. /upload/2019-09-09/a.png 当前时间作为子目录,避免一个目录下文件过多
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//3. 创建文件目录
File file = new File(path+date);
if (!file.exists()) {
file.mkdirs();
}
// 获取文件名
String fileName = imgFile.getOriginalFilename();
// UUID +"_"+ 文件名
String uniqueFileName = UUID.randomUUID().toString().replaceAll("-","")+"_"+fileName;
// 上传文件
imgFile.transferTo(new File(file,uniqueFileName));
return "success";
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |