文件下载a

article/2025/10/12 18:56:14

文章目录

  • 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,不想单独写就直接用以下方式实现
在这里插入图片描述


http://chatgpt.dhexx.cn/article/a8xZu03m.shtml

相关文章

GitHub 下载单个文件/文件夹

来源&#xff1a; github下载单个文件和目录_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1rL411K7Mx?spm_id_from333.880.my_history.page.click 步骤&#xff1a; 下单个文件&#xff1a; 1.首先你给有途径访问到github 2.在浏览器&#xff08;Edge&#xff09;扩…

Tabby sftp 下载文件夹

目录 Tabby介绍 下载文件夹 Tabby介绍 Tabby是一个基于 TypeScript 开发的终端模拟器&#xff0c;适用于 Windows&#xff0c;macOS 和 Linux。 可使用SSH、SFTP连接本地和服务器。 下载文件夹 下载文件直接选择本地编辑即可&#xff0c;但是不支持直接操作文件目录&#…

在GitHub 上下载指定的文件夹的两种方法

一、下载所有文件 首先介绍下如果你要下载GitHub下所有的项目文件的话,可以点击其主页下的Clone or download下的Download Zip ,可以直接下载到本地电脑;或者复制其链接,如下 然后再打开Git Bash,前提是你需要电脑已经下载安装好了Git,不会看我上篇安装Git文章。

【google drive 下载整个文件夹】

google drive 下载整个文件夹失败&#xff0c;提示 "try enable third party cookies" refs方法 refs https://support.google.com/drive/answer/2423534?hlen#zippy%2Cblocked-third-party-cookies-can-prevent-drive-web-downloads 方法 在谷歌浏览器地址栏输入…

从github上下载文件,文件夹,整个项目

一、下载文件 1、点进文件&#xff0c;如下图&#xff0c;然后右键红框 2、选择‘将链接另存为’&#xff0c;会出现以下界面 3、然后下载就可以。如果你成功了&#xff0c;恭喜你&#xff01;但是我失败了。。。 不晓得是我电脑的原因还是别的什么&#xff0c;尝试好多次都不…

通过下载链接,下载文件到指定的文件夹下

本文仅仅为了记录问题和解决办法&#xff0c;原文链接&#xff1a;https://www.cnblogs.com/rumengqiang/p/11156267.html 需求如题目所说&#xff0c;已知下载的链接url&#xff0c;和要保存的路径&#xff0c;将文件保存到指定的路径下&#xff1a; /*** 通过url&#xff0…

怎么从GitHub下载文件夹

方法1&#xff1a;右上角的下载按钮 方法2&#xff1a;没有下载按钮&#xff0c;复制GitHub网址输入到这个网站Gitzip下载&#xff1a;http://kinolien.github.io/gitzip/

Github | 如何在Github上只下载一个文件或文件夹!?

1写在前面 用过github的小伙伴们都知道&#xff0c;我们可以通过git clone命令来下载整个项目到本地。&#x1f618; 但我最近在使用github的时候遇到一个问题&#xff0c;就是我只想下载这一个文件&#xff0c;其他的我都不想要。&#x1fae0; 解决方案大家往下看吧&#xff…

下载文件夹的解决方案

ASP.NET批量下载文件的方法 这篇文章主要介绍了ASP.NET批量下载文件的方法,实例汇总了常见的asp.net实现批量下载的方法,具有一定的实用价值,需要的朋友可以参考下 本文实例讲述了ASP.NET批量下载文件的方法。分享给大家供大家参考。具体方法如下&#xff1a; 一、实现步骤 …

Ftp 下载文件夹

今天给大家分享一下使用Ftp 下载文件夹 首先说一下 流程&#xff0c; 我们需要用java代码先将我们需要下载的文件夹压缩成一个zip文件 然后我们在用户下载文件的方法 去下载这个zip 就可以 第一步 我们需要导入两个包 <dependency><groupId>com.jcraft</group…

web下载文件夹

1、文件下载有两种方式&#xff1a;一种是超链接&#xff0c;一种是Servlet提供下载。 2、超链接下载时&#xff1a;当文件可以在网页直接打开时&#xff0c;会直接打开文件&#xff0c;而不是下载&#xff0c;当文件打开不了时&#xff0c;会提供下载窗口。 3、超链接下载原…

List数组转换JSON格式

最近在写java&#xff0c;然后leader需要几个接口&#xff0c;里面的东西就是json格式。然后需求明白后&#xff0c;想了想思路:先把需要的东西从库里拿出来放到一个数组里面&#xff0c;然后再将数组转换成json&#xff0c;大体思路确定后&#xff0c;开始敲代码。 首先List一…

java中map、list转json

1、需导入的jar包 commons-beanutils-1.8.0.jar commons-collections-3.2.1.jar commons-lang-2.6.jar commons-logging-1.1.1.jar ezmorph-1.0.6.jar json-lig-2.4-jdk15.jar xom-1.2.6.jar 可自行网上下载 2、 3.List转成json格式 3、map转json 4、 参考&#xff…

Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap

Fastjson实用工具类&#xff0c;List转JSONString&#xff0c;List转JSONArray&#xff0c;JSONArray转List&#xff0c;JSONArray转ArrayList&#xff0c;JSONObject转HashMap 问题背景Fastjson转换心得Lyric&#xff1a;我们拥有 问题背景 因为经常用到fastjson&#xff0c;…

java中好用的list转json的工具hutool

java中好用的list转json的工具hutool 最近做服务器接口开发的时候遇到的小问题&#xff0c;数据库查询之后的数据怎样快捷的转化为json数据&#xff0c;第一时间想到了查库 查了挺久的&#xff0c;好多都是用代码实现&#xff0c;比较懒&#xff0c;这方面内容代码实现的偏多…

list转json

Struts2中list转换为json jar包下载地址 所需jar包&#xff0c;如下图&#xff1a; 实现代码&#xff0c;这里以execute方法为例&#xff1a; Overridepublic String execute() throws Exception {//1.调用Service根据typecode获得数据字典对象listList<BaseDict> l…

json与对象互转:json转实体类、实体类转json、json转List、List转json

目录 使用fastjson和Gson实现&#xff1a;实体类与json互转&#xff0c;List与json互转1. 实体类转json数据1.1 fastjson:1.2 Gson&#xff1a; 2. json转实体类2.1 fastjson&#xff1a;2.2 Gson: 3. List集合转json3.1 fastjson:3.2 Gson&#xff1a; 4. JSON转List集合4.1 f…

方法重写与重载的区别

1、方法重载 重载&#xff08;Overload&#xff09; 是在一个类里面&#xff0c;但方法的参数不同&#xff0c;包括参数的类型或者个数&#xff0c;返回值的类型可相同可不同。每一个重载的方法都有一个独一无二的参数列表。 最常用的地方就是构造器的重载。 2.方法重写 重写…

C#重写和重载的区别分析

一、前言 接触面向对象的思想已经有一段时光了&#xff0c;为什么要学习面向对象呢&#xff1f;因为面向对象具有可复用性、可维护性、可扩展性等优点。 刚学习完C#之后&#xff0c;难免会对重载和重写傻傻分不清楚。如今通过查阅资料对这两者有了一个大概的理解&#x…

【Java SE】重写和重载的区别

重写: 重写&#xff08;Override&#xff09;是父类与子类之间多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数&#xff0c;我们说该方法被重写 (Override)。子类的对象使用这个方法时&#xff0c;将调用子类中的定义&#xff0c;对它而言&#xff0c;父…