通过SpringMVC实现文件的上传和下载

一、导入jar包

1.commons-fileupload-1.3.1.jar
2.commons-io-2.2.jar
3.commons-logging-1.1.1.jar

7.spring-aop-4.0.0.RELEASE.jar
8.spring-beans-4.0.0.RELEASE.jar
9.spring-context-4.0.0.RELEASE.jar
10.spring-core-4.0.0.RELEASE.jar
11.spring-expression-4.0.0.RELEASE.jar
12.spring-web-4.0.0.RELEASE.jar
13.spring-webmvc-4.0.0.RELEASE.jar

二、文件的下载

1.前端代码:

<%@ 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>Insert title here</title>
</head>
<body>
<a href="downLoadFile?fileName=JDK1.6 API帮助文档.CHM">下载文件</a>
</body>
</html>

2.后端代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Encoder;

@Controller
public class DownLoadController{

	//@ResponseBody该注解作用告诉服务器响应的不是页面,而是文件资源
	@ResponseBody
	@RequestMapping(value = "/downLoadFile")
	public ResponseEntity<byte[]> downLoadFile(String fileName, HttpSession session, HttpServletRequest request) throws Exception {
		String realPath = session.getServletContext().getRealPath("upLoad");
		//获取文件在服务器的真实路径位置
		File file = new File(realPath + File.separator + fileName);
		// 解决文件名中文乱码问题
		String header = request.getHeader("User-Agent");
		if (header != null && header.contains("Firefox")) {
			fileName = "=?utf-8?B?" + new BASE64Encoder().encode(fileName.getBytes("utf-8")) + "?=";
		} else {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			byte[] body = new byte[fis.available()];
			fis.read(body);
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Disposition", "attachment;filename=" + fileName);
			HttpStatus statusCode = HttpStatus.OK;
			// 核心步骤,body为字节流,headers设置下载的文件名,statusCode服务器响应成功后的状态码
			ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, statusCode);
			return responseEntity;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//关闭流资源
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

3.运行结果:
在这里插入图片描述
三、单个文件的上传

1.前端代码:

	<form action="upLoadFile" method="post" enctype="multipart/form-data">
		<input type="file" name="file"><br>
		<input type="submit" value="上传">
	</form>

2.后端代码
注意:需要在springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		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-4.0.xsd">
	
	<context:component-scan base-package="com.atguigu"></context:component-scan>
	
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
		
	<!-- 配置文件上传解析器,id必须是"multipartResolver",否则会报错误 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 配置文件上传的编码格式与上传文件的最大值 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxUploadSize" value="5242880"></property>
	</bean>
	
	<!-- 解决静态资源访问不到的情况 -->
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>

</beans>

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UpLoadFileController {

	@RequestMapping(value = "/upLoadFile", method = RequestMethod.POST)
	// 通过MultipartFile接受前端传输过来的文件
	public String upLoadFile(MultipartFile file, HttpServletRequest request) {
		InputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			inputStream = file.getInputStream();
			String realPath = request.getSession().getServletContext().getRealPath("upLoad");
			String fileName = file.getOriginalFilename();
			File file2 = new File(realPath + File.separator + fileName);
			outputStream = new FileOutputStream(file2);
			// 通过apache提供的IOUtils工具类直接将文件复制到指定位置,指定位置就是服务器下的真实路径
			IOUtils.copy(inputStream, outputStream);
			return "success";
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

3.运行结果:
在这里插入图片描述
四、多个文件的上传

1.前端代码:

	<form action="upLoadFile" method="post" enctype="multipart/form-data">
		<input type="file" name="file"><br>
		<input type="file" name="file"><br>
		<input type="submit" value="上传">
	</form>

2.后端代码
注意:需要在springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		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-4.0.xsd">
	
	<context:component-scan base-package="com.atguigu"></context:component-scan>
	
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
		
	<!-- 配置文件上传解析器,id必须是"multipartResolver",否则会报错误 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 配置文件上传的编码格式与上传文件的最大值 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxUploadSize" value="5242880"></property>
	</bean>
	
	<!-- 解决静态资源访问不到的情况 -->
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>

</beans>

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UpLoadFileController {
	@RequestMapping(value = "/upLoadFiles", method = RequestMethod.POST)
	// 通过MultipartFile接受前端传输过来的多个文件
	public String upLoadFiles(@RequestParam(value="file") MultipartFile[] files, HttpServletRequest request) throws IOException {
		String realPath = request.getSession().getServletContext().getRealPath("upLoad");
		for (MultipartFile file : files) {
			String fileName = file.getOriginalFilename();
			File file2 = new File(realPath + File.separator + fileName);
			//使用springmvc本身自带的transferTo方法直接将文件传输到指定位置,也就是服务器下的真实路径
			file.transferTo(file2);
		}
		return "success";
	}
}

3.运行结果:
在这里插入图片描述
注:这里文件上传使用两种方式上传,一种是通过apache提供的IOUtils工具类,另外一种是springmvc自带的transferTo方法,此外还有一种是最原始的,通过输出流实现,本文章没有涉及到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值