SpringMVC的文件上传与下载

本文介绍如何使用SpringMVC结合CommonsMultipartResolver实现文件上传与下载功能,包括必要的配置步骤及解决中文乱码问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用SpringMVC包装的解析器(CommonsMultipartResolver)进行文件上传控制 需要引入 apache的 common-fileupload组件包、commons-io、commons-lang、commons-logging等


jsp文件的编写:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'form.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  
	<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
		文件上传<input type="file" name="myFile" />
  		<input type="submit" />
  	</form>

	<a href="${pageContext.request.contextPath}/download.action?fileName=日志、学号.txt">下载文件</a>
	
	
  </body>
  
  
</html>


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">


	<!-- springmvc -->
	<filter>
		<filter-name>utf</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>utf</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 <filter>
  	<filter-name>myencode</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>

 <!-- servlet一般是不支持delete和put  所以要配置一个过滤器 -->
 <filter>
 	<filter-name>hidden</filter-name>
 	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
 </filter>
 <filter-mapping>
 	<filter-name>hidden</filter-name>
 	<url-pattern>/*</url-pattern>
 </filter-mapping>

  <!-- 配置action -->
  <servlet>
  	<servlet-name>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>
    <init-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>/WEB-INF/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>*.action</url-pattern>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>



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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"

	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd

">

	<!--  名称必须使用  multipartResolver 因为spring容器使用名称注入 文件上传解析器-->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="1048576"></property>
	</bean>

	<!-- 扫描spring注解 -->
	<context:component-scan base-package="cn.et"></context:component-scan>

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean id="myConvetor" class="cn.et.springmvc.lesson02.message.MyMessageConvertor">
				<property name="supportedMediaTypes">
					<list>
						<!-- 设置响应支持的类型 -->
						<value>text/html;charset=UTF-8</value>
						<!-- 设置请求body支持的类型 -->
						<value>application/x-www-form-urlencoded</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

</beans>


Action的接受方式——文件上传与下载:

package cn.et.springmvc.lesson02.file;

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

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class SpringIo {

	private String filePath="D:/file";
	
	/**
	 * 文件上传
	 * @param myFile
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value="/upload")
	public String upload(@RequestParam("myFile") MultipartFile myFile, HttpServletResponse response) throws IllegalStateException, IOException{
		String fileName = myFile.getOriginalFilename();
		String destFile = filePath+"/"+fileName;
		myFile.transferTo(new File(destFile));
		response.getWriter().println("upload success");
		return null;
	}
	
	/**
	 * 文件下载
	 * @param myFile
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value="/download")
	public ResponseEntity<byte[]> download(String fileName) throws IOException{
		//需要下载的目标文件
		File file = new File("D:/file/"+fileName);
		//读取目标文件为二进制数组
		byte[] fileByte = FileCopyUtils.copyToByteArray(file)/*FileCopyUtils是工具类,可以直接读取到file文件的byte[]字节数组*/;
		//设置响应头
		HttpHeaders hh = new HttpHeaders();
		//设置下载的文件的名称
		hh.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8")/* URLEncoder解决中文乱码问题*/);
	
		//构建ResponseEntity对象
		ResponseEntity<byte[]> re = new ResponseEntity<byte[]>(fileByte, hh, HttpStatus.CREATED/*成功的枚举  200*/);
		return re;
	}
}


如果上传下载出现文件名的乱码问题去看:解决SpringMvc限定请求方法POST推送数据出现的中文乱码问题

在web.xml添加org.springframework.web.filter.CharacterEncodingFilter过滤器即可


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值