对于想了解springboot单,多文件打包下载到客户端--工具类的读者,本文将提供新的信息,我们将详细介绍springboot多文件下载,并且为您提供关于C#多文件打包下载、java文件下载(单文件
对于想了解springboot单,多文件打包下载到客户端--工具类的读者,本文将提供新的信息,我们将详细介绍springboot 多文件下载,并且为您提供关于C# 多文件打包下载、java 文件下载(单文件下载,多文件打包下载)、java多文件打包下载方法、php多文件打包下载实现代码的有价值信息。
本文目录一览:- springboot单,多文件打包下载到客户端--工具类(springboot 多文件下载)
- C# 多文件打包下载
- java 文件下载(单文件下载,多文件打包下载)
- java多文件打包下载方法
- php多文件打包下载实现代码
springboot单,多文件打包下载到客户端--工具类(springboot 多文件下载)
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*文件下载导出
*/
public class ZipFileExport {
/**
* 文件导出下载到----客户端
* @param response
* @param filename
* @param path
*/
public void downImgClient(HttpServletResponse response, String filename, String path ){
if (filename != null) {
FileInputStream inputStream = null;
BufferedInputStream bs = null;
ServletOutputStream servletOutputStream = null;
try {
response.setHeader("Content-Type","application/octet-stream");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''''" + encodeName);
File file = new File(path);
inputStream = new FileInputStream(file);
bs =new BufferedInputStream(inputStream);
servletOutputStream = response.getOutputStream();
writeBytes(bs, servletOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
//servletOutputStream = null;
}
if (bs!=null){
bs.close();
}
if (inputStream != null) {
inputStream.close();
//inputStream = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//writeBytes()构造方法
private void writeBytes(InputStream in, OutputStream out) throws IOException {
byte[] buffer= new byte[1024];
int length = -1;
while ((length = in.read(buffer))!=-1){
out.write(buffer,0,length);
}
in.close();
out.close();
}
/**
* 单文件导出下载
* @param response
* @param filename
* @param path
*/
public void downImg(HttpServletResponse response, String filename, String path ){
if (filename != null) {
FileInputStream is = null;
BufferedInputStream bs = null;
OutputStream os = null;
try {
File file = new File(path);
if (file.exists()) {
is = new FileInputStream(file);
bs =new BufferedInputStream(is);
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = bs.read(buffer)) != -1){
os.write(buffer,0,len);
}
}else{
String error = "下载的文件资源不存在";
System.out.println(error);
}
}catch(IOException ex){
ex.printStackTrace();
}finally {
try{
if(is != null){
is.close();
}
if( bs != null ){
bs.close();
}
if( os != null){
os.flush();
os.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
downImgClient(response,filename,path);
}
}
/**
* 多文件打包下载
* @param response
* @param names 文件名集合
* @param paths 文件路径集合
* @param directoryPath //临时存放--服务器上--zip文件的目录
*/
public void FileDownload(HttpServletResponse response, List<String> names, List<String> paths,String directoryPath,String zipFileNameEn) {
File directoryFile=new File(directoryPath);
if(!directoryFile.isDirectory() && !directoryFile.exists()){
directoryFile.mkdirs();
}
//设置最终输出zip文件的目录+文件名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String zipFileName =zipFileNameEn+ formatter.format(new Date())+".zip";
String strZipPath = directoryPath+"/"+zipFileName;
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
File zipFile = new File(strZipPath);
try{
//构造最终压缩包的输出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i<paths.size() ;i++){
//解码获取真实路径与文件名
String realFileName = java.net.URLDecoder.decode(names.get(i),"UTF-8");
String realFilePath = java.net.URLDecoder.decode(paths.get(i),"UTF-8");
File file = new File(realFilePath)
if(file.exists())
{
zipSource = new FileInputStream(file);//将需要压缩的文件格式化为输入流
/**
* 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样这里的name就是文件名,
* 文件名和之前的重复就会导致文件被覆盖
*/
ZipEntry zipEntry = new ZipEntry(realFileName);//在压缩目录中文件的名字
zipStream.putNextEntry(zipEntry);//定位该压缩条目位置,开始写入文件到压缩包中
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
byte[] buf = new byte[1024 * 10];
while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
{
zipStream.write(buf, 0, read);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流
try {
if(null != bufferStream) {
bufferStream.close();
}
if(null != zipStream){
zipStream.flush();
zipStream.close();
}
if(null != zipSource){
zipSource.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//判断当前压缩文件是否生成存在:true-把该压缩文件通过流输出给客户端后删除该压缩文件
if(zipFile.exists()){
//发送给客户端
downImgClient(response,zipFileName,strZipPath);
//删除本地存储的文件
zipFile.delete();
}
}
}
C# 多文件打包下载
JS 文件
var Arrurl = [{ "name": "尽职调查.pdf" }, { "name": "简介.pdf" }, { "name": "信托合同.pdf" }];
//ajax调用ashx
$.ajax({
type: ''post'',
url: "../DownZip.ashx",
data: {
url: JSON.stringify(Arrurl), //需打包文件的文件名拼接json数组
GoodsName: "打包好", //打包后的压缩包名称
},
success: function (ret) {
//执行返回压缩包路径下载
window.location.href = ret;
}
})
ashx 文件
//产品名称
string GoodsName = context.Request["GoodsName"];
//JSON数组文件路径
var itemJson = new JavaScriptSerializer().Deserialize<List<Dictionary<string, string>>>(context.Request["url"].ToString());
//List集合 foreach循环添加路径
List<string> listFile = new List<string>();
foreach (var item in itemJson)
{
listFile.Add(@"D:\atmoney\files\UserPic\" + item["name"].ToString() + "");
}
//压缩包保存路径
string downzipurl = @"D:\atmoney\files\GoodsDownLoad\" + GoodsName + ".zip";
//执行打包
ZipFile(listFile, downzipurl, 0);
//返回文件路径
context.Response.Write(@"http://www.xx.cn/files/GoodsDownLoad/" + GoodsName + ".zip");
/// <summary>
/// 压缩duo个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipedFile">压缩后生成的压缩文件名</param>
public static void ZipFile(List<string> fileToZipS, string zipedFile, int Level)
{
foreach (string fileToZip in fileToZipS)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new System.IO.FileNotFoundException("指定要压缩的文件: " +fileToZip+ " 不存在!");
break;
}
}
using (FileStream ZipFile = File.Create(zipedFile))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
foreach (string fileToZip in fileToZipS)
{
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\"));
using (FileStream fs = File.OpenRead(fileToZip))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(Level);
ZipStream.Write(buffer, 0, buffer.Length);
}
}
ZipStream.Finish();
ZipStream.Close();
}
}
}
java 文件下载(单文件下载,多文件打包下载)
最近项目有需要写文件下载相关代码,这边提交记录下相关代码模块,写的不太好,后期再优化相关代码,有好的建议,可留言,谢谢。
1)单文件下载
public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){
//针对需求需要与需求沟通下载文件传递参数
//目前demo文件名是文件的hashCode值+后缀名的方式命名,可以默认该hashCode值为文件唯一id
String fileName = request.getParameter("fileName");
if(StringUtils.isBlank(fileName)){
return "文件名为空";
}
String filePath = request.getSession().getServletContext().getRealPath("/convert")+File.separator+fileName;//目前文件默认在该文件夹下,后续变动需修改
File downloadFile = new File(filePath);
if(downloadFile.exists()){
OutputStream out = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
if(downloadFile.isDirectory()){
return "路径错误仅指向文件夹";
}
out = response.getOutputStream();// 创建页面返回方式为输出流,弹出下载框
fis = new FileInputStream(downloadFile);
bis = new BufferedInputStream(fis);
response.setContentType("application/pdf; charset=UTF-8");//设置编码字符
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
byte[] bt = new byte[2048];
int size = 0;
while((size=bis.read(bt)) != -1){
out.write(bt, 0, size);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//关闭流
out.flush();
if(out != null){
out.close();
}
if(bis != null){
bis.close();
}
if(fis != null){
fis.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return "下载成功";
}else{
return "文件不存在!";
}
}
2)多文件打包下载
a) 下载指定文件夹下的文件,如果嵌套文件夹也支持(但文件名需要唯一)
public String zipDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{
String sourceFilePath = request.getSession().getServletContext().getRealPath("/convert");//文件路径
String destinFilePath = request.getSession().getServletContext().getRealPath("/fileZip");
String fileName = FileUtil.zipFiles(sourceFilePath, destinFilePath);
File file = new File(destinFilePath+File.separator+fileName);
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
if(file.exists()){
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream out = response.getOutputStream();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] bufs = new byte[1024 * 10];
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
out.write(bufs, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(bis != null){
bis.close();
}
if(out!=null){
out.close();
}
File zipFile = new File(destinFilePath+File.separator+fileName);
if(zipFile.exists()){
zipFile.delete();
}
}
}else{
return "文件压缩失败";
}
return "下载成功";
}
b) 下载指定文件夹下的所有文件,支持树型结构
public String zipDownloadRelativePath(HttpServletRequest request,HttpServletResponse response) {
String msg ="";//下载提示信息
String root = request.getSession().getServletContext().getRealPath("/convert");//文件路径
Vector<File> fileVector = new Vector<File>();//定义容器装载文件
File file = new File(root);
File [] subFile = file.listFiles();
//判断文件性质并取文件
for(int i = 0; i<subFile.length; i++){
if(!subFile[i].isDirectory()){//不是文件夹并且不为空
fileVector.add(subFile[i]);//装载文件
}else{//是文件夹,再次递归遍历文件夹里面的文件
File [] files = subFile[i].listFiles();
Vector v = FileUtil.getPathAllFiles(subFile[i],new Vector<File>());
fileVector.addAll(v);//把迭代的文件装到容器中
}
}
//设置文件下载名称
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = dateFormat.format(new Date())+".zip";
response.setHeader("Content-disposition", "attachment;filename=" + fileName);//如果有中文需要转码
//定义相关流
//用于浏览器下载响应
OutputStream out = null;
//用于读压缩好的文件
BufferedInputStream bis = null;//用缓存性能会好一些
//用于压缩文件
ZipOutputStream zos = null;
//创建一个空的zip文件
String zipBasePath = request.getSession().getServletContext().getRealPath("/fileZip");
String zipFilePath = zipBasePath+File.separator+fileName;
File zipFile = new File(zipFilePath);
try {
if(!zipFile.exists()){//不存在创建一个新的
zipFile.createNewFile();
}
out = response.getOutputStream();
//创建文件输出流
zos = new ZipOutputStream(new FileOutputStream(zipFile));
//循环文件,一个一个按顺序压缩
for(int i = 0;i< fileVector.size();i++){
System.out.println(fileVector.get(i).getName()+"大小为:"+fileVector.get(i).length());
FileUtil.zipFileFun(fileVector.get(i),root,zos);
}
//压缩完成以后必须要在此处执行关闭 否则下载文件会有问题
if(zos != null){
zos.closeEntry();
zos.close();
}
byte[] bt = new byte[10*1024];
int size = 0;
bis = new BufferedInputStream(new FileInputStream(zipFilePath),10*1024);
while((size=bis.read(bt,0,10*1024)) != -1){//没有读完
out.write(bt,0,size);
}
} catch (Exception e) {
e.printStackTrace();
}finally {//关闭相关流
try {
//避免出异常时无法关闭
if(zos != null){
zos.closeEntry();
zos.close();
}
if(bis != null){
bis.close();
}
if(out != null){
out.close();
}
if(zipFile.exists()){
zipFile.delete();//删除
}
} catch (Exception e2) {
System.out.println("流关闭出错!");
}
}
return "下载成功";
}
下载辅助工具类
package com.hhwy.fileview.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileUtil {
/**
* 把某个文件路径下面的文件包含文件夹压缩到一个文件下
* @param file
* @param rootPath 相对地址
* @param zipoutputStream
*/
public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){
if(file.exists()){//文件存在才合法
if(file.isFile()){
//定义相关操作流
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
//设置文件夹
String relativeFilePath = file.getPath().replace(rootPath+File.separator, "");
//创建输入流读取文件
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis,10*1024);
//将文件装入zip中,开始打包
ZipEntry zipEntry;
if(!relativeFilePath.contains("\\")){
zipEntry = new ZipEntry(file.getName());//此处值不能重复,要唯一,否则同名文件会报错
}else{
zipEntry = new ZipEntry(relativeFilePath);//此处值不能重复,要唯一,否则同名文件会报错
}
zipoutputStream.putNextEntry(zipEntry);
//开始写文件
byte[] b = new byte[10*1024];
int size = 0;
while((size=bis.read(b,0,10*1024)) != -1){//没有读完
zipoutputStream.write(b,0,size);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//读完以后关闭相关流操作
if(bis != null){
bis.close();
}
if(fis != null){
fis.close();
}
} catch (Exception e2) {
System.out.println("流关闭错误!");
}
}
}
// else{//如果是文件夹
// try {
// File [] files = file.listFiles();//获取文件夹下的所有文件
// for(File f : files){
// zipFileFun(f,rootPath, zipoutputStream);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
}
}
/*
* 获取某个文件夹下的所有文件
*/
public static Vector<File> getPathAllFiles(File file,Vector<File> vector){
if(file.isFile()){//如果是文件,直接装载
System.out.println("在迭代函数中文件"+file.getName()+"大小为:"+file.length());
vector.add(file);
}else{//文件夹
File[] files = file.listFiles();
for(File f : files){//递归
if(f.isDirectory()){
getPathAllFiles(f,vector);
}else{
System.out.println("在迭代函数中文件"+f.getName()+"大小为:"+f.length());
vector.add(f);
}
}
}
return vector;
}
/**
* 压缩文件到指定文件夹
* @param sourceFilePath 源地址
* @param destinFilePath 目的地址
*/
public static String zipFiles(String sourceFilePath,String destinFilePath){
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = dateFormat.format(new Date())+".zip";
String zipFilePath = destinFilePath+File.separator+fileName;
if (sourceFile.exists() == false) {
System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");
} else {
try {
File zipFile = new File(zipFilePath);
if (zipFile.exists()) {
System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
} else {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
} else {
//读取sourceFile下的所有文件
Vector<File> vector = FileUtil.getPathAllFiles(sourceFile, new Vector<File>());
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < vector.size(); i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(vector.get(i).getName());//文件不可重名,否则会报错
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(vector.get(i));
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.closeEntry();
zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return fileName;
}
}
这边自测试全部可以正常使用,代码质量不高,如果代码方面优化有好的建议,请多多留言。
java多文件打包下载方法
/**
* 根据文件,进行压缩,批量下载
* @param response
* @param files 文件转换成的byte字节流
* @throws Exception
*/
public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName){
try{
response.reset();
zipName = java.net.URLEncoder.encode(zipName, "UTF-8");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + zipName + ".zip");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(zos);
for(Entry<String, byte[]> entry : files.entrySet()){
String fileName = entry.getKey(); //每个zip文件名
byte[] file = entry.getValue(); //这个zip文件的字节
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
zos.putNextEntry(new ZipEntry(fileName));
int len = 0;
byte[] buf = new byte[10 * 1024];
while( (len=bis.read(buf, 0, buf.length)) != -1){
bos.write(buf, 0, len);
}
bis.close();
bos.flush();
}
bos.close();
}catch(Exception e){
e.printStackTrace();
}
}
php多文件打包下载实现代码
最近整理文档,搜刮出一个php多文件打包下载的实例代码,稍微整理精简一下做下分享。本文主要和大家介绍php多文件打包下载的实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
需要同时下载多个文件时,大部分浏览器都不支持多文件同时下载,可以采用JavaScript脚本动态生成多个链接,但是需要用户多次点击下载对话框,用户体验不好,并且有些浏览器还不兼容。此时多文件打包下载帮你解决这个问题。
$filename = "test.zip"; $datalist=array('./pubfile/1.jpg','./pubfile/2.jpg'); if(!file_exists($filename)){ $zip = new ZipArchive(); if ($zip->open($filename, ZipArchive::CREATE)==TRUE) { foreach( $datalist as $val){ if(file_exists($val)){ $zip->addFile( $val, basename($val)); } } $zip->close(); } } if(!file_exists($filename)){ exit("无法找到文件"); } header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename='.basename($filename)); //文件名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件 header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小 @readfile($filename);
相关推荐:
php多文件打包下载的两种方法实例
如何实现php多文件上传封装
立即学习“PHP免费学习笔记(深入)”;
如何实现php多文件上传
以上就是php多文件打包下载实现代码的详细内容,更多请关注php中文网其它相关文章!
今天关于springboot单,多文件打包下载到客户端--工具类和springboot 多文件下载的介绍到此结束,谢谢您的阅读,有关C# 多文件打包下载、java 文件下载(单文件下载,多文件打包下载)、java多文件打包下载方法、php多文件打包下载实现代码等更多相关知识的信息可以在本站进行查询。
本文标签: