准备工作说明
将实现demo需要的相关util先准备好,完整controller代码在最后,如果想节省时间可以直接跳过单个demo的说明。
package com.example.demo.util;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Description
* @Date 13:39 2021/1/5
**/
public class FileUtils {
/**
* @Description 生成一个唯一的文件名
* @param fileName:
**/
public static String newFileName(String fileName) {
return UUID.randomUUID().toString().replaceAll("-", "") + "_" + fileName;
}
public static void zipd(String zipTmp, List<File> files, HttpServletResponse response) {
File zipTmpFile = new File(zipTmp);
try {
if (zipTmpFile.exists()) {
zipTmpFile.delete();
}
zipTmpFile.createNewFile();
response.reset();
// 创建文件输出流
FileOutputStream fous = new FileOutputStream(zipTmpFile);
ZipOutputStream zipOut = new ZipOutputStream(fous);
zipFile(files, zipOut);
zipOut.close();
fous.close();
downloadZip(zipTmpFile, response);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* files打成压缩包
*
* @param files
* @param outputStream
*/
public static void zipFile(List files, ZipOutputStream outputStream) {
int size = files.size();
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
}
public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream IN = new FileInputStream(inputFile);
BufferedInputStream bins = new BufferedInputStream(IN, 512);
ZipEntry entry = new ZipEntry(inputFile.getName());
ouputStream.putNextEntry(entry);
int nNumber;
byte[] buffer = new byte[512];
while ((nNumber = bins.read(buffer)) != -1) {
ouputStream.write(buffer);
}
bins.close();
IN.close();
} else {
try {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
zipFile(files[i], ouputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
if (file.exists() == false) {
System.out.println("待压缩的文件目录:" + file + "不存在.");
} else {
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
// 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
File f = new File(file.getPath());
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return response;
}
}
文件上传
/**
* @Description 文件上传
* @Date 13:45 2021/1/5
* @param file:
**/
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
String filePath = "F:/MyProject";
File targetFile = new File(filePath);
//检测是否存在目录
if (!targetFile.exists()) {
//不存在新建文件夹
targetFile.mkdirs();
}
try {
FileOutputStream out = new FileOutputStream(filePath + "/" + FileUtils.newFileName(file.getOriginalFilename()));
out.write(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
log.error("文件上传失败");
return "uploading failure";
}
log.info("文件上传成功");
return "uploading success";
}
单个文件下载
/**
* @Description 单个文件下载
* @Date 13:45 2021/1/5
* @param response:
**/
@GetMapping("/download")
public String download(HttpServletResponse response) throws IOException {
//文件名
String fileName = "bb.txt";
String filePath = "F:/MyProject";
File file = new File(filePath + "/" + fileName);
//设置文件路径
if (file.exists()) {
response.setContentType("application/octet-stream");
response.addHeader("Content-type", "application/octet-stream");
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
return "download success";
} catch (Exception e) {
e.printStackTrace();
} finally {
bis.close();
fis.close();
}
}
return "failure";
}
多个文件打包zip下载
/**
* @Description 多个文件下载并打包成zip
* @Date 13:45 2021/1/5
* @param response:
**/
@GetMapping("/downloads")
public String downloads(HttpServletResponse response) {
String test1 = "F:\\MyProject\\aa.txt";
String test2 = "F:\\MyProject\\bb.txt";
File file1 = new File(test1);
File file2 = new File(test2);
List<File> files = new ArrayList<>();
files.add(file1);
files.add(file2);
if (file1.exists() && file2.exists()) {
String zipTmp = "key.zip";
FileUtils.zipd(zipTmp, files, response);
}
return "bb";
}
文件上传、单个文件下载、多个文件打包zip下载-完整controller实现
package com.example.demo.controller;
import com.example.demo.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* @Description
* @Date 13:44 2021/1/5
**/
@RestController
@RequestMapping("/hello")
@Slf4j
public class TestController {
/**
* @Description 文件上传
* @Date 13:45 2021/1/5
* @param file:
**/
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
String filePath = "F:/MyProject";
File targetFile = new File(filePath);
//检测是否存在目录
if (!targetFile.exists()) {
//不存在新建文件夹
targetFile.mkdirs();
}
try {
FileOutputStream out = new FileOutputStream(filePath + "/" + FileUtils.newFileName(file.getOriginalFilename()));
out.write(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
log.error("文件上传失败");
return "uploading failure";
}
log.info("文件上传成功");
return "uploading success";
}
/**
* @Description 单个文件下载
* @Date 13:45 2021/1/5
* @param response:
**/
@GetMapping("/download")
public String download(HttpServletResponse response) throws IOException {
//文件名
String fileName = "bb.txt";
String filePath = "F:/MyProject";
File file = new File(filePath + "/" + fileName);
//设置文件路径
if (file.exists()) {
response.setContentType("application/octet-stream");
response.addHeader("Content-type", "application/octet-stream");
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
return "download success";
} catch (Exception e) {
e.printStackTrace();
} finally {
bis.close();
fis.close();
}
}
return "failure";
}
/**
* @Description 多个文件下载并打包成zip
* @Date 13:45 2021/1/5
* @param response:
**/
@GetMapping("/downloads")
public String downloads(HttpServletResponse response) {
String test1 = "F:\\MyProject\\aa.txt";
String test2 = "F:\\MyProject\\bb.txt";
File file1 = new File(test1);
File file2 = new File(test2);
List<File> files = new ArrayList<>();
files.add(file1);
files.add(file2);
if (file1.exists() && file2.exists()) {
String zipTmp = "key.zip";
FileUtils.zipd(zipTmp, files, response);
}
return "success";
}
}
就
先
说
到
这
\color{#008B8B}{ 就先说到这}
就先说到这
在
下
A
p
o
l
l
o
\color{#008B8B}{在下Apollo}
在下Apollo
一
个
爱
分
享
J
a
v
a
、
生
活
的
小
人
物
,
\color{#008B8B}{一个爱分享Java、生活的小人物,}
一个爱分享Java、生活的小人物,
咱
们
来
日
方
长
,
有
缘
江
湖
再
见
,
告
辞
!
\color{#008B8B}{咱们来日方长,有缘江湖再见,告辞!}
咱们来日方长,有缘江湖再见,告辞!