我们经常会使用的一个功能是文件下载,既然有文件下载就会有文件上传,下面我们来看一下文件上传是如何实现的

首先准备好一个页面

<style type="text/css">
form{
margin:0px auto;
border:1px solid red;
width:500px;
padding:20px;
}
</style>
</head> <body>
<form action="${pageContext.request.contextPath }/frist.do" method="post" enctype="multipart/form-data">
<h1>文件上传</h1>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
<input type="submit" value="上传">
</form>
</body>

单文件上传

通过对文件的大小来判断是否有文件

通过文件的类型来判断是否是允许

@Controller
public class MyController {
@RequestMapping(value="/frist.do", method=RequestMethod.POST)
public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
if(uploadFile.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=uploadFile.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
uploadFile.transferTo(file);
}
return "welcome.jsp";
}
return "error.jsp";
}

applicationContext.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 配置包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
<property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
<!-- <property name="uploadTempDir" value="/upload"></property> -->
</bean>
<!-- mvc注解驱动 -->
<mvc:annotation-driven /> </beans>

web.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- ================spring mvc 适配器================ -->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- ================================================== --> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

多文件上传(多文件上传与单文件上传配置相同下面介绍一下不同的地方)

标记为红色的字段为多文件上传 与单文件上传的区别

 @RequestMapping(value="/firstdown.do")
public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{
for (MultipartFile item : uploadFile) { if(item.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=item.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
item.transferTo(file);
}
return "welcome.jsp";
}
}
return "error.jsp";
}

文件下载

<br> public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType
) throws Exception { request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null; //获取项目根目录
String ctxPath = request.getSession().getServletContext()
.getRealPath(""); //获取下载文件露肩
String downLoadPath = ctxPath+"/uploadFile/"+ storeName; //获取文件的长度
long fileLength = new File(downLoadPath).length(); //设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(storeName.getBytes("utf-8"), "ISO8859-1"));
//设置输出长度
response.setHeader("Content-Length", String.valueOf(fileLength));
//获取输入流
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
//输出流
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
//关闭流
bis.close();
bos.close();
}

下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do

或者通过JSP页面

<a href="./downloadFile/download" >下载</a> 

随机推荐

  1. LA 3401 - Colored Cubes

    解题报告:有n(1<=n<=4)个立方体,每个立方体的每一个面涂有一种颜色,现在要将这些立方体的某些面的颜色重新涂一下,使得这n个立方体旋转到某一种状态下,对应的面的颜色都相同. 这题可以 ...

  2. ubuntu13 安装并配置ssh,交换密钥

    1.下载安装sudo apt-get install ssh,若出现问题,可选择安装openssh-server,或ssh-server等 2.启动ssh,命令:sudo /etc/init.d/ss ...

  3. libvirt 命令行交互工具之virsh

    libvirt是当前主流VM最低层库.IBM PowerVM也不例外,libvirt是深入玩虚拟化必须玩转的东西; 简单测试玩玩libvirt 的virsh命令行交互工具, 你我都知libvirt大体 ...

  4. UVa 202 - Repeating Decimals

    给你两个数,问你他们相除是多少,有无限循环就把循环体括号括起来 模拟除法运算 把每一次的被除数记下,当有被除数相同时第一个循环就在他们之间. 要注意50个数之后要省略号...每一次输出之后多打一个回车 ...

  5. deinstall oracle 11g on linux

    deinstall oracle 11g on linux   From 11gR2, oracle provide us an deinstall tool. With that now we ca ...

  6. MySQL数据库——安装教程(5.7版本)

    一.配置MySQL数据库 1.解压绿色版mysql,并改名为mysql5.7,如下图 对比一下下图5.6以前的版本,少data目录(存放数据)和my-default.ini文件(配置信息) 二.安装服 ...

  7. UVALi 3263 That Nice Euler Circuit(几何)

    That Nice Euler Circuit [题目链接]That Nice Euler Circuit [题目类型]几何 &题解: 蓝书P260 要用欧拉定理:V+F=E+2 V是顶点数; ...

  8. linux centos6.8搭建 jdk 环境

    1. 上官网下载jdk1.8的包 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html ...

  9. Codeforces758B Blown Garland 2017-01-20 10:19 87人阅读 评论(0) 收藏

    B. Blown Garland time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  10. Gradle Goodness: Copy Files with Filtering

    Gradle Goodness: Copy Files with Filtering Gradle's copy task is very powerful and includes filterin ...