文章目录
- 1、单个文件选择路径下载
- 2、多个文件打包成zip,选择路径下载
- 3、打包下载选中的文件和文件夹
- 只通过前端就下载文件(网络URL)
- 设置下载文件的名称
- 补充
前端代码一个a标签,href就是要访问的controller的路径,以下是文件下载Java代码,chrome要选高级,然后配置,不然每次都保存默认位置,不会弹出另存框

1、单个文件选择路径下载
//文件下载@RequestMapping(value = "/downFile",method = RequestMethod.GET)public void downloadImage(String fileName,HttpServletRequest request, HttpServletResponse response) {//处理一下文件名,不然中文乱码fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");//文件路径String fileUrl = "C:\\test\\123.txt";if (fileUrl != null) {File file = new File(fileUrl);if (file.exists()) {response.setContentType("application/force-download");// 设置强制下载不打开response.addHeader("Content-Disposition","attachment;fileName=" + fileName);// 设置文件名byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;try {fis = new FileInputStream(file);bis = new BufferedInputStream(fis);OutputStream os = response.getOutputStream();int i = bis.read(buffer);while (i != -1) {os.write(buffer, 0, i);i = bis.read(buffer);}System.out.println("success");} catch (Exception e) {e.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}}}
2、多个文件打包成zip,选择路径下载
选择到的如果是文件夹,下载不了,可以查看———3、打包下载选中的文件和文件夹
以下是个工具类,云桌面写的代码,弄不出来,照着打就行,什么都不用改,传写好的文件数组和outputStream进来就行。
图片写错了,files不是文件的路径,是File的数组,已经传好路径了,类似{new File(“D:\123.txt”),new File(“D:\555.txt”)},然后传到下面的工具类,outputStream是respon的getOutPut方法得来的
3、打包下载选中的文件和文件夹
可以下载文件夹
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;public class ZipUtil {private static final int BUFFER_SIZE = 2 * 1024;/*** @param srcDir 压缩文件夹路径* @param out 压缩文件输出流* @param KeepDirStructure 是否保留原来的目录结构,* true:保留目录结构;* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(String[] srcDir, String outDir,boolean KeepDirStructure) throws RuntimeException, Exception {OutputStream out = new FileOutputStream(new File(outDir));long start = System.currentTimeMillis();ZipOutputStream zos = null;try {zos = new ZipOutputStream(out);List<File> sourceFileList = new ArrayList<File>();for (String dir : srcDir) {File sourceFile = new File(dir);sourceFileList.add(sourceFile);}compress(sourceFileList, zos, KeepDirStructure);long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) + " ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 递归压缩方法* @param sourceFile 源文件* @param zos zip输出流* @param name 压缩后的名称* @param KeepDirStructure 是否保留原来的目录结构,* true:保留目录结构;* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws Exception*/private static void compress(File sourceFile, ZipOutputStream zos,String name, boolean KeepDirStructure) throws Exception {byte[] buf = new byte[BUFFER_SIZE];if (sourceFile.isFile()) {zos.putNextEntry(new ZipEntry(name));int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}// Complete the entryzos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0) {if (KeepDirStructure) {zos.putNextEntry(new ZipEntry(name + "/"));zos.closeEntry();}} else {for (File file : listFiles) {if (KeepDirStructure) {compress(file, zos, name + "/" + file.getName(),KeepDirStructure);} else {compress(file, zos, file.getName(), KeepDirStructure);}}}}}private static void compress(List<File> sourceFileList,ZipOutputStream zos, boolean KeepDirStructure) throws Exception {byte[] buf = new byte[BUFFER_SIZE];for (File sourceFile : sourceFileList) {String name = sourceFile.getName();if (sourceFile.isFile()) {zos.putNextEntry(new ZipEntry(name));int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}zos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0) {if (KeepDirStructure) {zos.putNextEntry(new ZipEntry(name + "/"));zos.closeEntry();}} else {for (File file : listFiles) {if (KeepDirStructure) {compress(file, zos, name + "/" + file.getName(),KeepDirStructure);} else {compress(file, zos, file.getName(),KeepDirStructure);}}}}}}public static void main(String[] args) throws Exception {String[] srcDir = { "path\\Desktop\\java","path\\Desktop\\java2","path\\Desktop\\fortest.txt" };String outDir = "path\\Desktop\\aaa.zip";ZipUtil.toZip(srcDir, outDir, true);}
}
借鉴的地址
上面的代码给了写死的保存位置,不会弹出保存框。
如果是要前端下载,弹出保存框,另存到指定位置,改了一下入参,
改一下toZip,以下是改变后的toZip方法的代码,其它代码不变,调用的时候传入要打包下载的路径的数组和outputStream(response.getOutPutStream()得到)
/*** @param srcDir 压缩文件夹路径,可以是文件夹路径,也可以是文件路径* @param outputStream 压缩文件输出流,* @param KeepDirStructure 是否保留原来的目录结构,* true:保留目录结构;* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(String[] srcDir, boolean KeepDirStructure,OutputStream outputStream) throws RuntimeException, Exception {long start = System.currentTimeMillis();ZipOutputStream zos = null;try {zos = new ZipOutputStream(new BufferedOutStream(outputStream));List<File> sourceFileList = new ArrayList<File>();for (String dir : srcDir) {File sourceFile = new File(dir);sourceFileList.add(sourceFile);}compress(sourceFileList, zos, KeepDirStructure);long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) + " ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}
只通过前端就下载文件(网络URL)
var url = $(this).attr("url"); //网络文件地址var xhr = new XMLHttpRequest();xhr.open('GET', url, true); // 也可以使用POST方式,根据接口xhr.responseType = "blob"; // 返回类型blob// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑xhr.onload = function () {// 请求完成if (this.status === 200) {// 返回200var blob = this.response;var reader = new FileReader();reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情hrefreader.onload = function (e) {// 转换完成,创建一个a标签用于下载var a = document.createElement('a');a.download = '中标通知书.pdf';a.href = e.target.result;$("body").append(a); // 修复firefox中无法触发clicka.click();$(a).remove();}}};// 发送ajax请求xhr.send()
设置下载文件的名称
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"))
补充
2021年1月27日15:21:19
ajax下载文件是弹不出另存为框的,要用form,不想单独写就直接用以下方式实现