springmvc文件上传下载

使用springmvc 上传和下载文件,首先创建maven工程整合ssm框架不赘述,加入jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>cn.e3mall</groupId>
    <artifactId>e3-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>cn.nxr</groupId>
  <artifactId>nxr-service</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  	<!-- Spring -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-beans</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aspects</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jms</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context-support</artifactId>
	</dependency>
	<!-- JSP相关 -->
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jsp-api</artifactId>
		<scope>provided</scope>
	</dependency>
	<!-- 数据库相关 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
	</dependency>
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis-spring</artifactId>
	</dependency>
	<dependency>
		<groupId>com.github.miemiedev</groupId>
		<artifactId>mybatis-paginator</artifactId>
	</dependency>
	<dependency>
		<groupId>com.github.pagehelper</groupId>
		<artifactId>pagehelper</artifactId>
	</dependency>
	<!-- MySql -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<!-- 连接池 -->
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid</artifactId>
	</dependency>
	<!-- Jackson Json处理工具包 -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
	</dependency>
	<!-- Apache工具组件 -->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-io</artifactId>
	</dependency>
	<dependency>
		<groupId>commons-net</groupId>
		<artifactId>commons-net</artifactId>
	</dependency>
	<!-- 文件上传组件 -->
	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
	</dependency>
  </dependencies>
  <!-- 配置tomcat插件 -->
  <build>
  	<plugins>
  		<plugin>
  			<groupId>org.apache.tomcat.maven</groupId>
  			<artifactId>tomcat7-maven-plugin</artifactId>
  			<configuration>
  				<path>/</path>
  				<port>9088</port>
  			</configuration>
  		</plugin>
  	</plugins>
  </build>
</project>

再在springmvc.xml中加入multipartResolver的配置

<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 上传文件大小上限,单位为字节(10MB) -->
        <property name="maxUploadSize">  
            <value>10485760</value>  
        </property>  
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

然后写一个上传的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>
    <form action="/upload" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>文件描述:</td>
                <td><input type="text" name="description"></td>
            </tr>
            <tr>
                <td>请选择文件:</td>
                <td><input type="file" name="file"></td>
            </tr>
            <tr>
                <td><input type="submit" value="上传"></td>
            </tr>
        </table>
    </form>
</body>
</html>

然后写Controller中的上传方法

@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public String uploadFile(String description,MultipartFile file,
							HttpServletRequest request) {
		if(!file.isEmpty()) {
			//上传文件路径
			String path = request.getSession().getServletContext().getRealPath("/images");
			//上传文件名
			String fileName = file.getOriginalFilename();
			File filePath = new File(path+File.separator+fileName);
			if(!filePath.getParentFile().exists()) {
				filePath.getParentFile().mkdir();
			}
			//将上传文件保存到目标文件中
			try {
				file.transferTo(filePath);
			} catch (Exception e) {
				e.printStackTrace();
				return "failed";
			}
			return "success";
		}else {
			return "failed";
		}
	}

注意点使用MultipartFile对象来绑定上传的文件即可。文件上传的路径使用Stringpath = request.getSession().getServletContext().getRealPath("/images");获取服务的根路径的时候不管在linux还是windows系统下

最后的分隔符会被过滤掉。然后路径的分隔符用File.separator来表示避免不同操作系统的路径分隔符不一致问题

用Object接收上传的文件只需要封装一个pojo,来作为controller的参数类型,上传多个文件只需要传入MultipartFile[] 数组作为参数用for循环逐个上传即可

下载文件只需获取到下载的路径用ResponseEntity对象以流的形式返回即可,注意的中文的编码问题不然会出现乱码。

下面是具体的jsp和java代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册</title>
</head>
<body>
    <h2>用户注册</h2>
    <form action="register" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>请上传头像:</td>
                <td><input type="file" name="image"></td>
            </tr>
            <tr>
                <td><input type="submit" value="注册"></td>
            </tr>
        </table>
    </form>
</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下载</title>
</head>
<body>
<h3>文件下载</h3>
<a href="download?filename=${requestScope.user.image.originalFilename}">
   ${requestScope.user.image.originalFilename }
</a>
</body>
</html>
@RequestMapping("register")
	public String register(HttpServletRequest request,
					@ModelAttribute User user) {
		//判断上传文件是否为空
		if(!user.getImage().isEmpty()) {
			//定义上传的路径
			String path = request.getSession().getServletContext().getRealPath("/images");
			//获取文件名
			String pathName = user.getImage().getOriginalFilename();
			//生成目标路径
			File filePath = new File(path+File.separator+pathName);
			//判断文件所在路劲是否存在
			if(!filePath.getParentFile().exists()) {
				filePath.getParentFile().mkdir();
			}
			//将文件保存到目标路径
			try {
				user.getImage().transferTo(filePath);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
				return "error";
			}
			return "userInfo";
		}else{
			return "error";
		}
	}
	
	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,String filename) throws Exception {
		//下载的路径
		String path = request.getSession().getServletContext().getRealPath("/images");
		System.out.println(path);
		filename = new String(filename.getBytes("iso-8859-1"),"utf-8");
		File file = new File(path+File.separator+filename);
		if(!file.exists()) {
			System.out.println("文件存在");
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment",filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值