Spring MVC实现文件的上传和下载--Day3

一:新建包controller

1:在包下新建MyController类

package controller;



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
	
	/*
	 * 判断要进行的功能
	 */
	@RequestMapping("judgeController")
	public String judgeController(String function) {
		if(function.equals("fileUpload")) {
			return "fileUpload.jsp";
		}
		else if(function.equals("fileDownload")){
			return "fileDownload.jsp";
		}
		else {
			return "fileQueryController";
		}
	}
	/*
	 * 查询目录下所有文件的文件名
	 */
	@RequestMapping("fileQueryController")
	public String fileQueryController(HttpServletRequest request) {
		HttpSession session=request.getSession();
		ArrayList<String> fileNameList=new ArrayList<>();
		File fileFolder=new File(request.getServletContext().getRealPath("/upload/"));
		File[] files=fileFolder.listFiles();
		for(File file:files) {
			fileNameList.add(file.getName());
		}
		session.setAttribute("fileNameList", fileNameList);
		return "fileQuery.jsp";
	}
    /*
     * 上传文件
     */
	@RequestMapping(value="fileUploadController",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String fileUploadController(HttpServletRequest request) throws IOException, FileUploadException {
		//创建DiskFileItemFactory工厂对象
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//设置文件缓存目录,如果该目录不存在则创建一个
		File f=new File("D:\\TempFolder");
		if(!f.exists()) {
			f.mkdirs();
		}
		//设置文件的缓存路径
		factory.setRepository(f);
		//创建ServletFileUpload对象
		ServletFileUpload fileUpload=new ServletFileUpload(factory);
		//解析request,得到上传文件的FileItem对象
		List<FileItem> fileItems=fileUpload.parseRequest(request);
		//存储文件信息
		String value = null;
		//遍历集合
		for(FileItem fileItem:fileItems) {
			//判断是否为普通字段
			if(fileItem.isFormField()) {
				String name=fileItem.getFieldName();
				if(name.equals("name")) {
					//如果文件不为空,将其保存在value中
					if(!fileItem.getString().equals("")) {
						value=fileItem.getString("utf-8");
						value="<p>上传者:"+value+"</p>";
					}
				}
			}
			else {
				//获得上传的文件名
				String fileName=fileItem.getName();
				//处理上传文件
				if(fileName!=null&&!fileName.equals("")) {
					value=value+"<p>上传的文件是:"+fileName+"</p>";
					//判断文件名是否有\\
					int flag=0;
		            for(int i=0;i<fileName.length();i++) {
		            	if(fileName.charAt(i)=='\\') {
		            		flag=1;
		            		break;
		            	}
		            }
					if(flag==1) {
						//截取出文件名
						fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
					}
					
					//文件名需要唯一
					fileName=UUID.randomUUID().toString()+"_"+fileName;
					
					
					//在服务器创建同名文件
					String webPath="/upload/";
					String filePath=request.getServletContext().getRealPath(webPath+fileName);
					//创建文件
					File file=new File(filePath);
					file.getParentFile().mkdirs();
					file.createNewFile();
					//获得上传文件流
					InputStream in=fileItem.getInputStream();
					FileOutputStream out = new FileOutputStream(file);
					//每次传输1K,传完为止
					byte[] buffer=new byte[1024];
					int len;
					while((len=in.read(buffer))>0) {
						out.write(buffer, 0, len);
						out.flush();
					}
					//删除临时文件
					fileItem.delete();
					//关闭流
					in.close();
					out.close();
					value=value+"<p>上传文件成功!</p>";
				}
			}
		}
	    return value;        	        
	}
	/*
	 * 下载文件
	 */
	@RequestMapping("fileDownloadController")
	@ResponseBody
	public String FileDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		//设置ContenttType编码
		response.setContentType("text/html;charset=utf-8");
		//设置相应消息编码
		response.setCharacterEncoding("utf-8");
		//设置请求消息编码
		request.setCharacterEncoding("utf-8");
		//获取下载文件的名称
		String fileName=request.getParameter("fileName");
		System.out.println(fileName);
		//对文件名称编码
		fileName=new String(fileName.trim().getBytes("UTF-8"),"UTF-8");
		//下载为文件所在目录
		String folder="/upload/";
		//通知浏览器以下载的形式打开
		response.addHeader("Content-Type", "application/octet-stream");
		response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
		InputStream in=request.getServletContext().getResourceAsStream(folder+fileName);
		OutputStream out=response.getOutputStream();
		byte[] buffer=new byte[1024];
		int len=-1;
		while((len=in.read(buffer))!=-1)
		{
			out.write(buffer,0,len);
			out.flush();
		}
		out.close();
		in.close();
		return "<p>下载成功</p>";
		
	}
}

二:新建jsp

1:index.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>index</title>
<style type="text/css">
body{
	position: absolute;
	left:47%;
	top:47%;
}
</style>
</head>
<body>
<form action="judgeController" method="post">
	<p>
		<select name="function">
			<option value="fileUpload">上传</option>
			<option value="fileDownload">下载</option>
			<option value="fileQuery">查询</option>
		</select>
	</p>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>

2:fileQuery.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.ArrayList" %>
<!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>
<style type="text/css">
body{
	position: absolute;
	left:43%;
	top:10%;
}
</style>
</head>
<body>
<%
	ArrayList<String> fileNameList=(ArrayList<String>)session.getAttribute("fileNameList");
	for(String fileName:fileNameList){
		out.print("<p>"+fileName+"</p>");
	}
%>
</body>
</html>

3:fileUpload.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>
<style type="text/css">
body{
	position: absolute;
	left:40%;
	top:40%;
}
</style>
</head>
<body>
<form action="fileUploadController" method="post" enctype="multipart/form-data">
	<p>上传者:&nbsp;&nbsp;&nbsp;<input type="text" name="name"/></p>
	<p>上传文件:<input type="file" name="file"/></p>
	<p><input type="submit" name="submit" value="上传"/></p>
</form>
</body>
</html>

4:fileDownload.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<!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>
<style type="text/css">
body{
	position: absolute;
	left:43%;
	top:43%;
}
</style>
</head>
<body>
<form action="fileDownloadController" method="post">
	<p><input type="text" name="fileName"/></p>
	<p><input type="submit" name="submit" value="下载"/><p>
</form>
</body>
</html>

三:配置文件

1: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>spring-mvc3</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>springmvc1</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc1</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置字符编码过滤器 -->
  <filter>
  	<filter-name>encoding</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>encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

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: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.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="controller"></context:component-scan>
	<!-- 注解驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 静态资源 -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
</beans>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值