一、文件上传

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

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

  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. 怎么给word加底纹

  2. 注意@Bean中的initMethod和destroyMethod

    @Configuration public class AppConfig { @Bean(initMethod = "init") public Foo foo() { retu ...

  3. Java中文乱码问题(转)

    解决JSP中文乱码问题 大家在JSP的开发过程中,经常出现中文乱码的问题,可能一至困扰着大家,现把JSP开发中遇到的中文乱码的问题及解决办法写出来供大家参考.首先了解一下Java中文问题的由来: Ja ...

  4. Windows Server 2008 R2 Upgrade Paths

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

  5. commons

    <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --> <dependency> <g ...

  6. HDU5748---(记录每个元素的 最长上升子序列 nlogn)

    分析: 给一个序列,求出每个位置结尾的最长上升子序列 O(n^2) 超时 #include "cstdio" #include "algorithm" #def ...

  7. macos装多个python

    简介 Mac包管理工具brew: 安装方法:命令行输入 /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Ho ...

  8. 【洛谷 P4168】[Violet]蒲公英(分块)

    题目链接 题目大意:给定\(n\)个数和\(m\)个求区间众数的询问,强制在线 这题我\(debug\)了整整一个下午啊..-_- 从14:30~16:45终于\(debug\)出来了,\(debug ...

  9. [bzoj3223]文艺平衡树——splay

    题意 你应当编写一个数据结构,支持以下操作: 反转一个区间 题解 我们把在数组中的位置当作权值,这样原序列就在这种权值意义下有序,我们考虑使用splay维护. 对于操作rev[l,r],我们首先把l- ...

  10. bzoj 1412 最小割 网络流

    比较明显的最小割建模, 因为我们需要把狼和羊分开. 那么我们连接source和每个羊,流量为inf,代表这条边不能成为最小割中的点,同理连接每个狼和汇,流量为inf,正确性同上,那么对于每个相邻的羊和 ...