SpringMVC笔记八之文件上传下载

本文介绍如何在SpringMVC框架中实现文件上传和下载功能。包括普通文件上传、基于对象的文件上传及文件下载的详细步骤和代码示例。

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

一、文件上传

1、普通文件上传

新建页面WebContent/file.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>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
   文件描述:<input type="text" name="desc"/><br/>
   选择文件:<input type="file" name="myfile"/><br/>
   <input type="submit" value="上传">
</form>
</body>
</html>

新建控制器src/controller/FileUploadController.java

package kshon.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import kshon.pojo.FileUpload;

@Controller
public class FileUploadController {

	@RequestMapping(value="upload",method=RequestMethod.POST)
	public String upload(HttpServletRequest request,
			@RequestParam("desc") String desc,
			@RequestParam("myfile") MultipartFile myfile){
		System.out.println(desc);
		if(!myfile.isEmpty()){
			//获取上传路径
			String path = request.getServletContext().getRealPath("/images/");
			//获取上传文件名
			String filename = myfile.getOriginalFilename();
			System.out.println("路径:"+path+filename);
			File filepath = new File(path,filename);
			if(!filepath.getParentFile().exists()){
				filepath.getParentFile().mkdirs();
				System.out.println("创建目录成功");
			}
			//将上传的文件保存到目标路径中
			try {
				myfile.transferTo(filepath);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return "success";
		}
		return "error";
	}

WEB-INF/web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
     <servlet-name>springmvc</servlet-name>
     <!-- 前端控制器 -->
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <!-- contextConfigLocation是参数名称,该参数的值包含的是springmvc的配置文件路径 -->
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/springmvc-config.xml</param-value>
     </init-param>
     <!-- 在web应用程序启动时立即加载Servlet -->
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置监听器 -->
  <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 指定spring的核心文件,必须使用context-param,ContextLoaderListener才能找到 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
  </context-param>

</web-app>

springmvc的配置文件WEB-INF/springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
        
       <!-- spring自动扫描base-package下面的包或子包下面的java文件(用了注解的java类必须被扫描才有效) -->
     <context:component-scan base-package="kshon.controller,kshon.pojo" />
       <!-- 设置配置方案 -->
     <mvc:annotation-driven />
       <!-- 使用默认的servlet响应静态文件 -->
     <mvc:default-servlet-handler/>
       <!-- 配置annotation类型的处理映射器 -->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
       <!-- 配置annotation类型的处理器适配器 -->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
       <!-- 视图解析器 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix">
             <value>/WEB-INF/content/</value>
         </property>
          <property name="suffix">
             <value>.jsp</value>
         </property>
     </bean>
     
     <!-- 国际化 -->
     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basenames" value="message"></property>
     </bean>
     <!-- 国际化操作拦截器如果采用基于(session/cookie)则必须配置 -->
     <mvc:interceptors>
       <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
     </mvc:interceptors>
     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
     
     <!-- 文件上传 -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件大小限制 -->
     	<property name="maxUploadSize">
     		<value>10485760</value>
     	</property>
     	<!-- 请求的编码格式,需与jsp页面的编码一致,方便正确读取,默认编码为ISO-8859-1 -->
     	<property name="defaultEncoding">
     		<value>UTF-8</value>
     	</property>
     </bean>
</beans>

运行tomcat,输入http://localhost:8080/SpringMVC/file.jsp

接下来在tomcat中的springMVC项目中查看

2、基于对象的文件上传

在src/pojo目录下新建一个FileUpload.java类

package kshon.pojo;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

	private String name;
	private MultipartFile file;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public MultipartFile getFile() {
		return file;
	}
	public void setFile(MultipartFile file) {
		this.file = file;
	}
}

在src/controller/FileUploadController.java中增加一个方法

@RequestMapping(value="fileUpload",method=RequestMethod.POST)
	public String fileUpload(@ModelAttribute FileUpload fileUpload,
			Model model,
			HttpServletRequest request){
		if(!fileUpload.getFile().isEmpty()){  //如果上传的文件不为空
			String path = request.getServletContext().getRealPath("/images");  //获取项目路径下的images目录
			String filename = fileUpload.getFile().getOriginalFilename();   //获取上传的文件名
			File file = new File(path,filename);  //合并路径和文件名
			if(!file.getParentFile().exists()){  //判断images目录是否存在,不存在则创建
				file.getParentFile().mkdirs();
			}
			try {
				//将上传文件 移动到目标文件
				fileUpload.getFile().transferTo(file);
				//将上传文件信息存到model
				model.addAttribute("fileUpload", fileUpload);
				System.out.println(path+File.separator+filename);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "filelist";
		}
		return "error";
		
	}

修改页面WebContent/file.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>Insert title here</title>
</head>
<body>
<form action="fileUpload" method="post" enctype="multipart/form-data">
   文件描述:<input type="text" name="name"/><br/>
   选择文件:<input type="file" name="file"/><br/>
   <input type="submit" value="上传">
</form>
</body>
</html>

启动tomcat,输入http://localhost:8080/SpringMVC/file.jsp

接下来在tomcat中的springMVC项目中查看

二、文件下载

在WEB-INF/content目录下新建filelist.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>Insert title here</title>
</head>
<body>
<a href="download?filename=${requestScope.fileUpload.file.originalFilename}">下载文件</a>
${requestScope.fileUpload.file.originalFilename}
</body>
</html>

在src/controller/FileUploadController.java中增加一个方法

@RequestMapping("download")
	public ResponseEntity<byte[]> download(HttpServletRequest request,
			@RequestParam("filename") String filename,
			Model model) throws IOException{
		//下载目录
		String path = request.getServletContext().getRealPath("/images");
		File file = new File(path,filename);
		//设置编码类型
		String downloadName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
		HttpHeaders headers = new HttpHeaders();
		//通知浏览器以attachment(下载文件)的方式打开浏览器
		headers.setContentDispositionFormData("attachment", downloadName);
		//application/octet-stream:二进制流数据(最常见的下载方式)
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}

启动tomcat,输入http://localhost:8080/SpringMVC/file.jsp

点击上传后,跳转到WEB-INF/content/filelist.jsp页面 

点击下载文件,即可看到文件选择框

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值