一、文件上传

  实现文件上传多数是采用表单提交数据,

  但对于进行文件上传的表单需要满足一下几个条件

  1.表单的method设置为post

  2.表单的enctype设置为multipart/form-data.

  3.拥有上传文件选择框<input type = "file" name = "filename"/>

<input id = "Files" name = "uploadFiles" type = "file"multiple = "multiple"/>

  设置multiple属性可以实现多文件上传,即一次选中多个文件然后上传。  

  表单中选择上传文件点击提交后,还需要有SpringMVC对其解析。

  使用SpringMVC的文件解析需要在xml中配置CommonsMultipartResolver.

      <bean id = "multipartResolver"
class = "org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name = "defaultEncoding" value = "UTF-8"/>
     </bean>

  defaultEncoding:默认编码格式。

  maxUploadSize:上传文件最大尺寸(单位为字节)

  maxInMemorySize:最大缓存尺寸()

  注:配置CommonsMultipartResolver时,Bean的ID需指定为multipartResolver.

  最后还需要导入两个jar包。

  commons-fileupload.x.x.x.jar:

  commons-io-x.x.jar:http://commons.apache.org/proper/commons-io/download_io.cgi

  上传的文件会被封装成MultipartFile,

  MultipartFile主要方法:

  byte[] getBytes():以字节数组形式返回文件内容。

  StringgetContentType();返回文件的内容类型。

  InputStream getInputStream();返回一个输入流,读取该文件内容。

  String getName()获取上传文件选择框的name属性的值。

  String getOriginalFilename();获取上传文件初始名。

  long getSize();获取文件大小,单位为字节。

  boolean isEmpty()判断文件是否为空。是空返回true。

  void transferTo(File file),将上传文件保存到file路径中。

  接下来我们看一个文件上传的实例:

  FileUpload.java (该类为POJO类,封装了上传文件及上传人姓名,作为参数类型传递到控制类方法中)

  注:POJO类属性名和元素name属性的值要一致。不一致可用过@RquestParam管理。

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {
public String name;//上传人姓名
public List<MultipartFile> uploadFiles;//上传文件
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<MultipartFile> getUploadFiles() {
return uploadFiles;
}
public void setUploadFiles(List<MultipartFile> uploadFiles) {
this.uploadFiles = uploadFiles;
}
}

控制类 FileControl:

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; @Controller
public class FileController {
List<String> fileList = new LinkedList<String>(); @RequestMapping("/fileUpload") //文件上传具体操作
public String fileUpload(FileUpload fileUpload, HttpServletRequest request) {
String name = fileUpload.getName();
//获取所有上传文件
List<MultipartFile> uploadFiles = fileUpload.getUploadFiles();
//文件原始名
String originalFilename = null;
//上传文件保存路径
String uploadFilesSavePath = null;
//根据保存路径创建文件夹
File filePath = null;
//UUID编码后的名称
String newFileName = null;
// //判断上传文件是否为空
if(!uploadFiles.isEmpty() && uploadFiles.size() > 0) {
//迭代所有上传文件
for(MultipartFile file : uploadFiles) {
//获取文件名称
originalFilename = file.getOriginalFilename();
//获取保存路径
uploadFilesSavePath = request.getServletContext().getRealPath("/upload/");
System.out.println("uploadFilesSavePath:" + uploadFilesSavePath);
//设置保存路径
filePath = new File(uploadFilesSavePath);
//文件夹为空则创建文件夹
if(!filePath.exists()) {
filePath.mkdirs();
}
//设置上传文件的行名称,添加UUID重命名。
newFileName = name + "_" + UUID.randomUUID() + "_" + originalFilename;
try {//将上传文件保存在指定目录下
file.transferTo(new File(uploadFilesSavePath + newFileName));
fileList.add(uploadFilesSavePath + newFileName);//记录上传文件路径信息
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("originalFilename" + originalFilename);
System.out.println("Filename" + file.getName()); }
//成功页面显示文件路径消息
request.setAttribute("fileList", fileList);
fileList.clear();//清空列表,用于下一次记录。
return "success";
}
return "error";
} @RequestMapping("/fileDownload")//文件下载具体操作
public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
String filePaht = request.getServletContext().getRealPath("/upload/");
File file = new File(filePaht + File.separator + filename);
System.out.print("downloadPaht:" + file.getPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
} @RequestMapping("/toUploadFile")//访问上传文件页面
public String toUploadFile() {
return "uploadFile";
} @RequestMapping("/toDownloadFile")//访问下载文件页面
public String toDownloadFile() {
return "downloadFile";
}
}

uploadFile.jsp  文件上传界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function check(){
var name = document.getElementById("name").value;
var uploadFiles = document.getElementById("Files").value;
if(name == null || name == ""){
alert("上传者姓名为空");
return false;
}
if(uploadFiles == "" || uploadFiles.length == 0 ){
alert("上传文件为空");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/fileUpload" onsubmit = "return check()"
enctype = "multipart/form-data" method = "post">
上传者姓名:<input id = name name = "name" type = "text" /><br>
上传文件:<input id = "Files" name = "uploadFiles" type = "file"
multiple = "multiple"/><br>
<input type = "submit" value = "上传文件" />
</form>
</body>
</html>

success.jsp  上传成功页面

<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
success <br/> <!--输出上传保存文件路径-->
<%
List<String> fileList = (LinkedList<String>)request.getAttribute("fileList");
for(String file : fileList){
out.println(file); }
%> </body>
</html>

二、文件下载

  下载文件主要通过设置一个<a>标签,通过超链接调用控制类中的下载方法, 

  调用超链接的同时要附加上相关信息,例如文件名等。

<a href = "${pageContext.request.contextPath}/fileDownload?filename=xxx.txt">下载xxx.txt</a>

  例如上述例子,通过调用控制类中的fileDownloader方法下载xxx.txt文件。

  

  下载方法具体实现:

  

@RequestMapping("/fileDownload")//文件下载具体操作
public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
List<String> fileList = new ArrayList<>();
//获取上传文件保存路径
String filePath = request.getServletContext().getRealPath("/upload/");
//通过fileName和保存路径,构建文件对象
File file = new File(filePath + File.separator + filename); System.out.print("downloadPath:" + file.getPath());
//获取响应头
HttpHeaders headers = new HttpHeaders();
//设置以下载方式打开文件
headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));
//设置以流的形式下载返回数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//使用SpringMVC中ResponseEntity返回下载数据
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
}

我们将下载,上传综合下都写在FileController中,

FileController.java

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; import com.sun.org.apache.bcel.internal.generic.NEW; @Controller
public class FileController {
List<String> fileList = new LinkedList<String>(); @RequestMapping("/fileUpload") //文件上传具体操作
public String fileUpload(FileUpload fileUpload, HttpServletRequest request) {
String name = fileUpload.getName();
//获取所有上传文件
List<MultipartFile> uploadFiles = fileUpload.getUploadFiles();
//文件原始名
String originalFilename = null;
//上传文件保存路径
String uploadFilesSavePath = null;
//根据保存路径创建文件夹
File filePath = null;
//UUID编码后的名称
String newFileName = null;
//
fileList.clear();//清空列表,用于下一次记录。
//判断上传文件是否为空 if(!uploadFiles.isEmpty() && uploadFiles.size() > 0) {
//迭代所有上传文件
for(MultipartFile file : uploadFiles) {
//获取文件名称
originalFilename = file.getOriginalFilename();
//获取保存路径
uploadFilesSavePath = request.getServletContext().getRealPath("/upload/");
System.out.println("uploadFilesSavePath:" + uploadFilesSavePath);
//设置保存路径
filePath = new File(uploadFilesSavePath);
//文件夹为空则创建文件夹
if(!filePath.exists()) {
filePath.mkdirs();
}
//设置上传文件的行名称
newFileName = name + "_" + UUID.randomUUID() + "_" + originalFilename;
try {//将上传文件保存在指定目录下
file.transferTo(new File(uploadFilesSavePath + newFileName));
fileList.add(uploadFilesSavePath + newFileName);//记录上传文件路径信息
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("originalFilename" + originalFilename);
System.out.println("Filename" + file.getName()); }
//成功页面显示文件路径消息
request.setAttribute("fileList", fileList); return "success";
}
return "error";
} @RequestMapping("/fileDownload")//文件下载具体操作
public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
List<String> fileList = new ArrayList<>();
//获取上传文件保存路径
String filePath = request.getServletContext().getRealPath("/upload/");
//通过fileName和保存路径,构建文件对象
File file = new File(filePath + File.separator + filename); System.out.print("downloadPath:" + file.getPath());
//获取响应头
HttpHeaders headers = new HttpHeaders();
//设置以下载方式打开文件
headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));//此处对文件名进行编码,防止中午乱码。
//设置以流的形式下载返回数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//使用SpringMVC中ResponseEntity返回下载数据
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
} @RequestMapping("/toUploadFile")//访问上传文件页面
public String toUploadFile() {
return "uploadFile";
} @RequestMapping("/toDownloadFile")//访问下载文件页面,并传递文件列表
public String toDownloadFile(HttpServletRequest request) {
//获取文件存放路径
String filePath = request.getServletContext().getRealPath("/upload/");
//构建文件对象
File downloadFileList = new File(filePath);
//将upload文件夹下所有文件名传递给页面
request.setAttribute("downloadFileList", downloadFileList.list());
return "downloadFile";
}
}

downloadFile.jsp    下载页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import = "java.io.File" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String[] files = (String[])request.getAttribute("downloadFileList");
//输出可下载文件列表
for(String file : files){
out.println("<a href = "+ request.getContextPath() +"/fileDownload?filename="+ file +">" + file +"</a><br>");
}
%> </body>
</html>

1.6(Spring MVC学习笔记)文件上传与下载的更多相关文章

  1. Spring MVC学习笔记——文件上传

    1.实现文件上传首先需要导入Apache的包,commons-fileupload-1.2.2.jar和commons-io-2.1.jar 实现上传就在add.jsp文件中修改表单 enctype= ...

  2. spring mvc 简单的文件上传与下载

    上传文件有很多种方法,这里主要讲解的是spring mvc内提供的文件上传 前提使用:spring mvc 在这个之前我们需要把环境给配置好 1:springmvc的XML配置文件加上这一段就即可, ...

  3. 关于我使用spring mvc框架做文件上传时遇到的问题

    非常感谢作者 原文:https://blog.csdn.net/lingirl/article/details/1714806 昨天尝试着用spring mvc框架做文件上传,犯了挺多不该犯的毛病问题 ...

  4. javaWeb学习总结——文件上传、下载

    目录 1.文件上传环境搭建 2.文件上传代码实现 3.关于下载 @ 嘿,熊dei,你不得不知道在Web开发中,文件上传和下载功能是非常常用的功能,关于文件上传,浏览器上传[文件以流的形式传输]--&g ...

  5. JavaWeb学习总结——文件上传和下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  6. Struts2学习总结——文件上传与下载

    Struts2文件上传与下载 1.1.1新建一个Maven项目(demo02) 在此添加Web构面以及 struts2 构面 1.2.1配置Maven依赖(pom.xml 文件) <?xml v ...

  7. 【Spring学习笔记-MVC-13.2】Spring MVC之多文件上传

    作者:ssslinppp       1. 摘要 前篇文章讲解了单文件上传<[Spring学习笔记-MVC-13]Spring MVC之文件上传>http://www.cnblogs.co ...

  8. spring mvc中的文件上传

    使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...

  9. spring MVC multipart处理文件上传

    在开发Web应用程序时比较常见的功能之一,就是允许用户利用multipart请求将本地文件上传到服务器,而这正是Grails的坚固基石——Spring MVC其中的一个优势.Spring通过对Serv ...

随机推荐

  1. deploy a ec2 and join into domain with terraform

    Below is the example to convert the ps script into userdata for terraform to create instance and aut ...

  2. Windows Server 2008 R2 Upgrade Paths

    https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd ...

  3. xcode 10 新特性

    这里主要介绍一下Xcode10 版本主要更新的内容.随着iOS12的发布,Xcode10已经可以从Mac App Store下载.Xcode10包含了iOS12.watchOS 5.macOS10.1 ...

  4. 随机洗牌算法Knuth Shuffle和错排公式

    Knuth随机洗牌算法:譬如现在有54张牌,如何洗牌才能保证随机性.可以这么考虑,从最末尾一张牌开始洗,对于每一张牌,编号在该牌前面的牌中任意一张选一张和当前牌进行交换,直至洗到第一张牌为止.参考代码 ...

  5. html5 游戏开发

    近来想做html5游戏开发些小东西玩一下,因为手边就是笔记本,想怎么玩就怎么玩了,今年可以说是非常重要特殊的一年,感觉有些倒霉,不过,心态最重要,该怎么做的时候就去怎么做吧,日子的24小时是不会变的, ...

  6. [Leetcode Week8]Subsets II

    Subsets II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/subsets-ii/description/ Description Given ...

  7. TCP三次握手四次分手

    TCP(Transmission Control Protocol) 传输控制协议 TCP是主机对主机层的传输控制协议,提供可靠的连接服务,采用三次握手确认建立一个连接: 位码即tcp标志位,有6种标 ...

  8. 1.hadoop环境搭建以及配置

    提前说明一下:由于环境的配置搞得我很头疼,所以记录下来.并不是零基础,像hadoop的由来.发展史.结构.各个组件,这里都没有介绍,只是为了自己能够在忘了的时候回忆起来,所以记录下来 如何在linux ...

  9. 使用MybatisGenerator自动生成Model,Mapping和Mapper文件

    Mybatis和Hibernate都是持久层框架,MyBatis出现的比Hibernate晚,这两种框架我都用过,对于二者的优势我的感触不深,个人感觉MyBatis自动生成model,Mapping, ...

  10. [BZOJ1853][Scoi2010]幸运数字 容斥+搜索剪枝

    1853: [Scoi2010]幸运数字 Time Limit: 2 Sec  Memory Limit: 64 MBSubmit: 3202  Solved: 1198[Submit][Status ...