一、文件上传

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

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

  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. [hdu 3068] Manacher算法O(n)最长回文子串

    一个不错的讲解:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.05.md # ...

  2. angular的一些问题

    引入第三方类库 1.安装依赖 npm install jquey --save 2.引入项目 在angular-cli.json "scripts": [ "../nod ...

  3. Switf与OC混合开发流程

    看着身边越来越多的小伙伴转入Swift,本人也跟随潮流,转战Swift了~下面是初步写入的一个Swift项目框架. 1.创建项目,这个应该不用说了,语言swift 2.CocoaPods 导入第三方 ...

  4. Django项目知识点汇总

    目录 一.wsgi接口 二.中间件 三.URL路由系统 四.Template模板 五.Views视图 六.Model&ORM 七.Admin相关 八.Http协议 九.COOKIE 与 SES ...

  5. js错误处理

    导致程序无法继续执行的异常状态称为错误. js中一旦发生错误,就会自动创建一个Error类型对象 js中有6中错误类型: SyntaxError 语法错误 ReferenceError 引用错误,找不 ...

  6. 不谈OI:高二(13)最后一次班班有歌声

    最后一次班班有歌声了…… 自己因为搞oi并没有参加,只是决赛的时候幕后放了放背景视频…… 不管怎么说,我们班唱的很棒啊,全部人都很棒! 说真的我为我们班骄傲 视频: https://v.qq.com/ ...

  7. swift mac 使用git, 并使用osc, 打开当前目录命令在终端输入 open . windows 下为start .

    使用git.osc而不用github, 因为在osc里面可以设置私有项目,而不需要公开. ssh-keygen -t rsa -C "email@email.com" mac下生成 ...

  8. Ansible 创建用户 Playbook 脚本

    创建用户,设置wheel组sudo不需要密码,然后将用户添加到wheel组,并将用户的公钥传输到节点上: --- - name: Linux Create User and Upload User P ...

  9. loggin

    # 参考:https://www.cnblogs.com/DI-DIAO/p/8793136.html BASE_LOG_DIR = os.path.join(BASE_DIR, "log& ...

  10. java 聊天程序

    package cn.apr.chart; import java.net.*; import java.io.*; import java.util.*; public class ChatServ ...