一、文件上传
实现文件上传多数是采用表单提交数据,
但对于进行文件上传的表单需要满足一下几个条件
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>

来源:https://www.cnblogs.com/huang-changfan/p/10423089.html