1.导入jar包:
springmvc的jar包
apache的关于文件上传的jar:commons-fileupload.jar和commons-io.jar
2.配置文件:
web.xml中的配置如下:
<!-- 配置dispatcherServlet -->
<servlet>
<servlet-name>springmvc</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--字符编码过滤器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
springmvc.xml的配置如下:
<!-- 扫描 -->
<context:component-scan base-package="com.sxt.controller"/>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:resources location="/file/" mapping="/file/**"></mvc:resources>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置multipartResolver解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
编写控制器层的代码:
1)文件下载:
@RequestMapping("download")
public void downlaod(String fileName,HttpServletRequest req,HttpServletResponse resp) throws IOException{
System.out.println(fileName);
//设置响应流中文件进行下载
resp.setHeader("Content-Disposition", "attachment;filename=bbb.txt");
//把二进制流放入到响应体中
ServletOutputStream os = resp.getOutputStream();
String path = req.getServletContext().getRealPath("file");
System.out.println(path);
File file = new File(path, fileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
os.write(bytes);
os.flush();
os.close();
}
文件下载的页面:
<a href="download?fileName=a.txt">下载</a>
2)文件上传:
@RequestMapping("upload")
public String upload(MultipartFile file,String username) throws IOException{
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/"+uuid+suffix));
return "main";
}
文件上传的页面:
<form action="upload" enctype="multipart/form-data" method="post">
姓名:<input type="text" name="username"/><br/>
文件:<input type="file" name="file" /><br />
<input type="submit" value="提交" />
</form>