文件的上传和下载
准备工作
1, 依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2, 上传的< from>页面
<form action="${path}/upload/upload" enctype="multipart/form-data" method="post">
<label class="btn btn-primary" for="fileup" style="float: left">
选择文件
</label>
<input type="file" name="file" id="fileup" style="display:none;">
<div style="width:320px;float: left">
<input type="text" id="fileshow" class="form-control" value="" readonly>
</div>
<button class="btn btn-default" type="submit">上 传</button>
</form>
3,下载页面
<button onclick="" class="btn btn-link">下载</button>
<a href=""> <button class="btn btn-link">在线打开</button></a>
4,配置上传文件的大小
SpringBoot 在application.yml 中配置
默认最大文件为1MB 一次请求最大为 10MB
spring:
http:
multipart:
max-file-size: 200MB
max-request-size: 1000MB
上传
在Controller 层进行上传代码搭建
A:上传到项目上
public String upload(MultipartFile file, HttpSession sn) throws IOException {
/**
* 以日期为文件名 每天在项目上创建一个新的文件夹
* */
//获取当前日期yyyy-MM-dd
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String s = format.format(new Date());
//获取目录的真实位置
String realPath = sn.getServletContext().getRealPath(s + "/");
//判断路径是否存在,不存在便创建
File file1 = new File(realPath);
if (!file1.exists()) {
file1.mkdir();
}
//获取uuid
String id = UUID.randomUUID().toString();
//为了防止重复上传因文件名相同而冲突id和原文件名合成新名
String name = id + filename;
//上传文件
file.transferTo(new File(realPath + "/" + name));
}
B 删除项目上的文件
new File(“带文件名的路径”).delete();
获取文件的一些信息
//获取文件原始名带后缀
String filename = file.getOriginalFilename();
//获取后缀名
String substring = filename.substring(filename.lastIndexOf("."));
//获取文件类型
String contentType = file.getContentType();
//获取文件大小
long size = file.getSize();
//判断原文件是否为图片类型
String jugde = “否”;
if (contentType.startsWith(“image”)) {
jugde = “是”;
}
上传文件到文件系统上后续补充
下载
在线查看
public void unfold(String fname, String path, HttpSession sn, HttpServletResponse response) throws IOException {
//获取文件的所在路径
String realPath = sn.getServletContext().getRealPath(path);
//获取源文件的字节数组
byte[] bs = FileUtils.readFileToByteArray(new File(realPath));
//设施相应头信息
response.setHeader("content-disposition", "attachment:filename" + URLEncoder.encode(fname, "UTF-8"));
//获取输出流
ServletOutputStream outputStream = response.getOutputStream();
//使用输出流输出
outputStream.write(bs);
//看完删除本地的
new File(realPath).delete();
}
从项目中下载
public String download(Integer ss, String originalname, String id, String download, String fname, String path, HttpSession sn, HttpServletResponse response) throws IOException {
String realPath = sn.getServletContext().getRealPath(path);
//获取源文件的字节数组
byte[] bs = FileUtils.readFileToByteArray(new File(realPath));
//设施相应头信息
response.setContentType("application/force-download");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(originalname, "utf-8"));
//获取输出流
ServletOutputStream outputStream = response.getOutputStream();
//使用输出流输出
outputStream.write(bs);
//下载完删除本地的
new File(realPath).delete();
}