SpringMVC入门 文件上传和下载

1.创建一个web项目,并且导入所需要的jar包
在这里插入图片描述
2.在web.xml文件中,配置SpringMVC的前端控制器等等信息
web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    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_3_0.xsd">
 <servlet>
 	<servlet-name>springmvc</servlet-name>
 	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 	<init-param>
 		<param-name>contextConfigLocation</param-name>
 		<!-- 加载springmvc-config.xml -->
 		<param-value>classpath:springmvc-config.xml</param-value>
 	</init-param>
 	<load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 	<servlet-name>springmvc</servlet-name>
 	<url-pattern>/</url-pattern>
 </servlet-mapping>
 	<!-- 处理post请求的中文乱码-->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

3.在src目录下,创建并编写SpringMVC的核心配置文件springmvc-config.xml
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:context="http://www.springframework.org/schema/context"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!-- 配置包扫描 -->
		<context:component-scan base-package="com.zzp.controller"/>
		<!-- 配置注解驱动 -->
		<mvc:annotation-driven/>
		<!-- 配置视图解析器 -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<!-- 设置前缀 -->
			<property name="prefix" value="/WEB-INF/jsp/"/>
			<!-- 设置后缀 -->
			<property name="suffix" value=".jsp"/>
		</bean>
		<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置请求编码格式,必须与jsp中的pageEncoding属性一致,默认为ISO-8859-1 -->
		<property name="defaultEncoding" value="utf-8"/>
		<!-- 设置允许上传文件的最大值(2MB),单位为字节 -->
		<property name="maxUploadSize" value="2097152"></property>
		</bean>
</beans>

4.在WebRoot目录下,创建一个用于上传文件的页面fileUpload.jsp
fileUpload.jsp:

<%@page import="java.net.URLEncoder"%>
<%@ 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>上传文件测试</title>
  </head>
  
  <body>
   <form action="${pageContext.request.contextPath }/file/tolist" method="post" enctype="multipart/form-data">
   	<input type="file" name="uploadfile" multiple="multiple">
  	<input type="submit" value="上传文件">
   </form>
   <a href="${pageContext.request.contextPath }/file/download?filename=<%=URLEncoder.encode("zzp2e42d343-b2f2-4f24-9bbd-ea5a34add67a_.jpeg", "utf-8") %>">下载壁纸</a>
  </body>
</html>

5.在WEB-INF目录下,创建jsp文件夹,在文件夹下创建show.jsp页面用来提示文件上传成功与失败
show.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>测试文件上传</title>
  </head>
  <body>
    ${msg }
  </body>
</html>

6.在src目录下,创建一个com.zzp.controller包,在该包下创建一个用于文件上传的控制器FileController
FileController:

package com.zzp.controller;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

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.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FileController {
	@RequestMapping("/tofile")
	public String toflie(){
		return "fileUpload";
	}
	@RequestMapping("/tolist")
	public String FileList(List<MultipartFile> uploadfile,HttpServletRequest request,Model m){
		//设置上传文件的保存地址目录
		String path=request.getServletContext().getRealPath("/upload/");
		//判断所上传的文件
		if(!uploadfile.isEmpty()&&uploadfile.size()>0){
			//循环输出上传的文件
			for(MultipartFile item:uploadfile){
				//获取上传文件的原始名称
				String oldFile=item.getOriginalFilename();
				//获取原始名称的的后缀
				String newFile=oldFile.substring(oldFile.lastIndexOf("."));
				File filepath=new File(path);
				//如果保存文件的地址不存在,就先创建目录
				if(!filepath.exists()){
					filepath.mkdirs();
				}
				//使用UUID重新命名上传文件名称
				String EndFile="李三"+UUID.randomUUID()+"_"+newFile;
				try {
					//MultipartFile接口的方法完成文件上传到指定位置
					item.transferTo(new File(filepath, EndFile));
					//存入成功信息,提示页面成功
					m.addAttribute("msg", "上传成功");
				} catch (Exception e) {
					e.printStackTrace();
					m.addAttribute("msg", "异常信息:"+e.getMessage());	
				} 
			}
		}
		//跳转到页面
		return "show";
	}
	@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws IOException{
		//filename文件名编码转换成UTF-8,如果是UTF-8格式文件名将会乱码,或者不转换文件名编码
		filename=new String(filename.getBytes("ISO-8859-1"),"UTF-8"); 
		//指定要下载的文件所在路径
		String path=request.getServletContext().getRealPath("/upload/");
		//创建该文件对象
		File file=new File(path+File.separator+filename);
		//对文件名编码,防止中文文件乱码
		filename=getFilename(request, filename);
		//设置响应头
		HttpHeaders headers=new HttpHeaders();
		//通知浏览器以下载的方式打开文件
		headers.setContentDispositionFormData("attachment", filename);
		//定义以流的形式下载返回文件数据
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//使用Spring MVC框架的ResponseEntity对象封装返回下载数据
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
	}
	public String getFilename(HttpServletRequest request,String filename) throws UnsupportedEncodingException{
		//IE不同版本User-Agent中出现的关键词
		String[] IEB={"MSIE","Trident","Edge"};
		//获取请求头代理信息
		String userAgent=request.getHeader("User-Agent");
		for(String keyWord:IEB){
			if(userAgent.contains(keyWord)){
				//IE内核浏览器,统一为utf-8编码显示
				return URLEncoder.encode(filename, "utf-8");
			}
		}
		//火狐等其他浏览器统一为ISO-8859-1编码显示
		return new String(filename.getBytes("utf-8"),"ISO-8859-1");
	}
}

7.启动项目,在浏览器中输入地址http://localhost:8080/SpringMVCFile/file/tofile,页面显示为:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值