springmvc批量将文件打包成zip下载
2016-12-26 15:28
357 查看
springMVC的代码
/**
* 一键下载图片
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "downUrl")
@CheckLogin
public void admin_applyloan_downUrl(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id) {
try {
//1.获取项目中文件的文件夹
String basePath = request.getSession().getServletContext().getRealPath("/") + Constants.RESOURCE_PATH;
//2.获取oss上的文件路径List集合:https://www.xxx.xx/xxx.jpg
ApplyLoan applyLoan = applyLoanService.getById(id);
List<String> urlListAll = new ArrayList<String>();
List<String> urlList = (List<String>) applyLoan.getParamsMap().get("carImg");
List<String> ownerList = (List<String>) applyLoan.getParamsMap().get("ownerImg");
urlListAll.addAll(urlList);
urlListAll.addAll(ownerList);
//3.定义文件list
List<File> files = new ArrayList<File>();
//4.定义zip文件名
String fileName = UUID.randomUUID().toString() + ".zip";
//4.1定义临时单个文件的list,方便后面删除
List<String> tempUrlList = new ArrayList<String>();
//5.将文件从https上下载进服务器的目录,用files装好
for (String url : urlListAll) {
URL u = new URL((String) request.getServletContext().getAttribute("imagePath") + url);
String tempUrl = basePath +System.currentTimeMillis()+ url.substring(url.lastIndexOf("."));
File f = new File(tempUrl);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream ins = u.openStream();
OutputStream os = new FileOutputStream(f);
int bytesRead = 0;
byte[] buffer = new byte[2048];
while ((bytesRead = ins.read(buffer, 0, 2048)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
files.add(f);
tempUrlList.add(tempUrl);
}
//6.创建zip文件
ZipUtil.createFile(basePath, fileName);
File file = new File(basePath + fileName);
FileOutputStream outStream = new FileOutputStream(file);
ZipOutputStream toClient = new ZipOutputStream(outStream);
//7.将files打包成zip文件
ZipUtil.zipFile(files, toClient);
toClient.close();
outStream.close();
//8.下载zip文件,并删除服务器源文件
ZipUtil.downloadFile(file, response, true);
//9.删除服务器临时的单个文件
for(String t : tempUrlList){
DeleteFileUtil.delete(t);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @version 1.0
* 删除文件
* */
public class DeleteFileUtil {
/**
* 删除文件,可以是文件或文件夹
* @param fileName 要删除的文件名
* @return 删除成功返回true,否则返回false
*/
public static boolean delete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("删除文件失败:" + fileName + "不存在!");
return false;
} else {
if (file.isFile())
return deleteFile(fileName);
else
return deleteDirectory(fileName);
}
}
}
zip压缩代码
/**
* zip压缩文件
*/
public class ZipUtil {
/**
* 压缩文件列表中的文件
*
* @param files
* @param outputStream
* @throws IOException
*/
public static void zipFile(List<File> files, ZipOutputStream outputStream)
throws IOException, ServletException {
try {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
/**
* 将文件写入到zip文件中
*
* @param inputFile
* @param outputstream
* @throws Exception
*/
public static void zipFile(File inputFile, ZipOutputStream outputstream)
throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(
inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);
final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
long streamTotal = 0; // 接受流的容量
int streamNum = 0; // 流需要分开的数量
int leaveByte = 0; // 文件剩下的字符数
byte[] inOutbyte; // byte数组接受文件的数据
streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量
if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// 读入流,保存在byte数组
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
}
}
// 写出剩下的流数据
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); // 关闭
inStream.close();
}
} else {
throw new ServletException("文件不存在!");
}
} catch (IOException e) {
throw e;
}
}
/**
* 下载文件
*
* @param file
* @param response
*/
public static void downloadFile(File file, HttpServletResponse response,
boolean isDelete) {
try {
// 以流的形式下载文件。
BufferedInputStream 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");
response.setHeader("Content-Disposition",
"attachment;filename="
+ new String(file.getName().getBytes("UTF-8"),
"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if (isDelete) {
file.delete(); // 是否将生成的服务器端文件删除
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 创建文件
* @param path
* @param fileName
*/
public static void createFile(String path, String fileName) {
File f = new File(path);
File file = new File(f, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上就可以从别的服务器,采用地址批量打包下载代码了
/**
* 一键下载图片
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "downUrl")
@CheckLogin
public void admin_applyloan_downUrl(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id) {
try {
//1.获取项目中文件的文件夹
String basePath = request.getSession().getServletContext().getRealPath("/") + Constants.RESOURCE_PATH;
//2.获取oss上的文件路径List集合:https://www.xxx.xx/xxx.jpg
ApplyLoan applyLoan = applyLoanService.getById(id);
List<String> urlListAll = new ArrayList<String>();
List<String> urlList = (List<String>) applyLoan.getParamsMap().get("carImg");
List<String> ownerList = (List<String>) applyLoan.getParamsMap().get("ownerImg");
urlListAll.addAll(urlList);
urlListAll.addAll(ownerList);
//3.定义文件list
List<File> files = new ArrayList<File>();
//4.定义zip文件名
String fileName = UUID.randomUUID().toString() + ".zip";
//4.1定义临时单个文件的list,方便后面删除
List<String> tempUrlList = new ArrayList<String>();
//5.将文件从https上下载进服务器的目录,用files装好
for (String url : urlListAll) {
URL u = new URL((String) request.getServletContext().getAttribute("imagePath") + url);
String tempUrl = basePath +System.currentTimeMillis()+ url.substring(url.lastIndexOf("."));
File f = new File(tempUrl);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream ins = u.openStream();
OutputStream os = new FileOutputStream(f);
int bytesRead = 0;
byte[] buffer = new byte[2048];
while ((bytesRead = ins.read(buffer, 0, 2048)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
files.add(f);
tempUrlList.add(tempUrl);
}
//6.创建zip文件
ZipUtil.createFile(basePath, fileName);
File file = new File(basePath + fileName);
FileOutputStream outStream = new FileOutputStream(file);
ZipOutputStream toClient = new ZipOutputStream(outStream);
//7.将files打包成zip文件
ZipUtil.zipFile(files, toClient);
toClient.close();
outStream.close();
//8.下载zip文件,并删除服务器源文件
ZipUtil.downloadFile(file, response, true);
//9.删除服务器临时的单个文件
for(String t : tempUrlList){
DeleteFileUtil.delete(t);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @version 1.0
* 删除文件
* */
public class DeleteFileUtil {
/**
* 删除文件,可以是文件或文件夹
* @param fileName 要删除的文件名
* @return 删除成功返回true,否则返回false
*/
public static boolean delete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("删除文件失败:" + fileName + "不存在!");
return false;
} else {
if (file.isFile())
return deleteFile(fileName);
else
return deleteDirectory(fileName);
}
}
}
zip压缩代码
/**
* zip压缩文件
*/
public class ZipUtil {
/**
* 压缩文件列表中的文件
*
* @param files
* @param outputStream
* @throws IOException
*/
public static void zipFile(List<File> files, ZipOutputStream outputStream)
throws IOException, ServletException {
try {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
/**
* 将文件写入到zip文件中
*
* @param inputFile
* @param outputstream
* @throws Exception
*/
public static void zipFile(File inputFile, ZipOutputStream outputstream)
throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(
inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);
final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
long streamTotal = 0; // 接受流的容量
int streamNum = 0; // 流需要分开的数量
int leaveByte = 0; // 文件剩下的字符数
byte[] inOutbyte; // byte数组接受文件的数据
streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量
if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// 读入流,保存在byte数组
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
}
}
// 写出剩下的流数据
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); // 关闭
inStream.close();
}
} else {
throw new ServletException("文件不存在!");
}
} catch (IOException e) {
throw e;
}
}
/**
* 下载文件
*
* @param file
* @param response
*/
public static void downloadFile(File file, HttpServletResponse response,
boolean isDelete) {
try {
// 以流的形式下载文件。
BufferedInputStream 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");
response.setHeader("Content-Disposition",
"attachment;filename="
+ new String(file.getName().getBytes("UTF-8"),
"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if (isDelete) {
file.delete(); // 是否将生成的服务器端文件删除
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 创建文件
* @param path
* @param fileName
*/
public static void createFile(String path, String fileName) {
File f = new File(path);
File file = new File(f, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上就可以从别的服务器,采用地址批量打包下载代码了
相关文章推荐
- Java实现文件自动打包成zip并下载的代码
- ThinkPHP实现将本地文件打包成zip下载
- 使用PHP自带zlib函数 几行代码实现PHP文件打包下载zip
- 【Java】Java实现批量打包文件Zip下载
- spring mvc java 把多文件打包成zip,并下载
- 文件zip打包,流式下载python 代码
- 使用PHP的ZipArchive类实现多个文件的zip压缩包打包下载
- 生成的Excel出力到指定文件夹生成Zip文件再打包这些文件到页面下载
- zip压缩打包文件下载
- [Java Web]服务器获取远程文件并Zip打包给客户端下载
- Java实现文件自动打包成zip并下载的代码
- 使用PHP自带zlib函数 几行代码实现PHP文件打包下载zip
- struts zip打包多个文件并下载
- ajax下载多文件,并且打包 C#中 ,文件批下载zip
- java 将多个文件打包成一个zip后进行下载
- ThinkPHP实现将本地文件打包成zip下载
- Java打包下载ZIP压缩文件
- meteor---在合并打包多个文件ZIP下载的功能
- 几行代码轻松实现PHP文件打包下载zip
- spingmvc 文件下载打包zip