一、文件上传

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

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

  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. swagger学习2

    转:http://blog.csdn.net/fansunion/article/details/51923720 写的非常好,非常详细,推荐!!!! 最常用的5个注解 @Api:修饰整个类,描述Co ...

  2. linux 服务器下入侵之后的日志清理

    1.web日志的清理:access.log 和auth.log 位置在/var/log/下面. 2.系统日志存放在:/root/.bash_history

  3. (转)Notepad++

    包括notepad++的详细的安装过程,插件使用说明,技巧…… crifan http://www.crifan.com/files/doc/docbook/rec_soft_npp/release/ ...

  4. vue2.0基础知识,及webpack中vue的使用

    ## 基础指令 ## [v-cloak]{         Display:none;     }     <p v-cloak>xx{{msg}}xx</p> //解决闪烁问 ...

  5. ViewPager使用--文章集锦

    viewpager中彻底性动态添加.删除Fragment Android ViewPager使用详解 fragment中嵌套viewpager,vierpager中有多个fragment,不显示 .. ...

  6. cglib

    参考:http://blog.csdn.net/zhoudaxia/article/details/30591941 <!-- https://mvnrepository.com/artifac ...

  7. Java中一些知识的归纳总结

    1.包装类型与基本数据类型的区别. Java语言是一个面向对象的语言,但是Java中的基本数据类型却是不面向对象的,这使得Java在实际使用时存在很多的不便,为了解决这个不足,在设计类时为每个基本数据 ...

  8. bzoj 1208 HNOI2004宠物收养所 平衡树

    裸平衡树,恢复手感用的 //By BLADEVIL var n :longint; i :longint; x, y :longint; t, tot :longint; key, s, left, ...

  9. postman接口间关联

    现有A.B两个接口,A接口返回的response的body中的部分数据,是B接口发起请求部分数据的来源. A接口response的body结构如下: { "address": &q ...

  10. C#字节数组的常用解码处理方法

    在某些情况下,比如说串口通信或者读取二进制的文件,通常会得到一个byte数组形式的数据. 然而对于这个数据处理常常令人苦恼,因为通常通信情况下,并不是一个字节代表一个字符或者某个数据,而是数据夹杂在字 ...