springBoot response实现文件下载

【SpringBoot笔记12】SpringBoot框架实现文件上传和文件下载 SpringBoot文件上传和下载,还是使用的SpringMVC框架中的,只不过SpringBoot给我们做了简化,它提供了一些文件上传的配置属性,例如:设置单个文件上传大小、单个请求最大上传文件大小、是否支持多文件上传等。下面介绍如何在SpringBoot框架中实现文件上传。 阅读详情
参考 :

https://www.jianshu.com/p/4c52cb691f54
https://blog.youkuaiyun.com/ios_xumin/article/details/52944366
关于response的相关介绍,请参考链接

response响应实现文件下载,主要有以下注意点:

  • 1.添加response响应头与媒体类型
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("multipart/form-data");
  • 2.response读取输出流并写出
IoUtil.writeFile(file, response.getOutputStream());
  • 3.页面访问对应接口,此处直接通过跳转访问
window.location.href = "path";

tool

public class IoUtil {
    /**
     * 写出
     * @param file
     * @param out
     */
    public static void writeFile(File file, OutputStream out) {
        FileInputStream fs = null;
        try{
            fs = new FileInputStream(file);
            //循环写入输出流
            byte[] b = new byte[1024*8];
            int len;
            while ((len = fs.read(b)) > 0) {
                out.write(b, 0, len);
            }
        }catch (Exception e){
            throw new RuntimeException("流写出错误");
        }finally {
            close(fs,out);
        }
    }

    /**
     * 关流
     */
    public static void close(InputStream is){
        if(is!=null){
            try{
                is.close();
                is = null;
            }catch (Exception e2){
                throw new RuntimeException("关闭流失败");
            }
        }
    }

    /**
     * 关流
     */
    public static void close(OutputStream os){
        if(os!=null){
            try{
                os.close();
                os = null;
            }catch (Exception e2){
                throw new RuntimeException("关闭流失败");
            }
        }
    }

    /**
     * 关流
     */
    public static void close(InputStream is , OutputStream os){
        if(is!=null){
            try{
                is.close();
                is = null;
            }catch (Exception e2){
                throw new RuntimeException("关闭流失败");
            }
        }
        if(os!=null){
            try{
                os.close();
                os = null;
            }catch (Exception e2){
                throw new RuntimeException("关闭流失败");
            }
        }
    }
}

具体实现就要结合业务了啊

先进封装基础知识 想象一下,芯片就像是电脑或手机的大脑,但它非常脆弱,需要被保护起来。芯片封装就是给芯片穿上一件“保护衣”,这件“保护衣”不仅可以保护芯片,还能帮助芯片与外部世界进行沟通。 阅读详情

相关推荐

PySide6多线程避坑大全:信号槽崩溃、内存泄漏,这些雷我都帮你踩过了

本文深入探讨了PySide6多线程开发中的常见问题与解决方案,包括信号槽崩溃、内存泄漏等典型陷阱。通过实战案例和优化策略,帮助开发者避免UI线程操作错误、有效管理资源生命周期,并提升跨线程通信的可靠性。特别针对PySide6多线程特性,提供了线程安全日志、死锁检测等实用调试技巧。

weixin_32288959的博客 397

SpringBoot实现文件下载的几种方式比较。

这里写自定义目录标题SpringBoot实现文件下载的几种方式比较基础版然后这里先引申出进阶版:主动关闭文件流。使用缓存流,边读边写 SpringBoot实现文件下载的几种方式比较 目前,网上一搜SpringBoot环境下载文件。有多种实现方式,大概率出来的会是基础版的,基础版的有几个坑,我这里分别将基础版以及基础版会出现的问题,从而引申各种解决方法。 基础版 话不多说,直接上源码: @RestController public class TestDownload { @Value("${gen.

sfhappy23的博客 7350

Elasticsearch连接中断:深入解析Connection reset by peer问题及优化策略

本文深入解析Elasticsearch连接中断问题,特别是Connection reset by peer错误的成因与解决方案。从TCP层的心跳机制到客户端与服务端的配置差异,详细介绍了网络不稳定、防火墙拦截等常见原因,并提供了六种优化策略,包括KeepAlive调整、TCP参数调优和智能重试机制等,帮助提升Elasticsearch连接的稳定性。

weixin_42546392的博客 411

SpringBoot实现文件上传和下载的功能

SpringBoot实现文件上传和下载的功能,并在在Swagger测试成功。

m0_52767002的博客 1366

ERGM指数随机图模型全解析:从基础原理到R语言实操

从社交网络中的互惠、传递性和同质性等基本现象切入,介绍网络数据与传统回归分析的本质差异——边与边之间的依赖关系。指数随机图模型(ERGM)正是为刻画这种依赖结构而设计的统计框架,它通过指数族分布将网络结构效应显式建模,结合MCMC方法完成参数估计。ERGM在组织协作、传播扩散、生物生态等领域的应用日益广泛,其扩展模型TERGM、GERGM和多层ERGM进一步支持时序、权重与多重关系网络。本文系统梳理ERGM的理论基础、核心统计量、扩展模型选型及R语言实操要点,帮助研究者理解网络生成机制并完成收敛性诊断与结果

weixin_29050271的博客 367

基于电子海图的水面无人艇全局路径规划

Research and Implementation of Global Path Planning for Unmanned Surface Vehicle Based on Electronic Chart (基于电子海图的水面无人艇全局路径规划)   该论文已经在ICMIR2017会议上发表,附上springer的文献地址 Research and Implementation of Gl...

weixin_30797199的博客 1591

基于SpringBoot项目做一个文件上传和下载

基与Springboot做个一文件上传和下载

weixin_56445565的博客 617

《用 R 探索医药数据科学》目录(持续更新,已超 250 万字)|订阅前说明

我们重磅推出《用 R 探索医药数据科学》专栏!本文作为专栏【订阅后首读】的核心内容,堪称开启学习之旅的 “入门钥匙”,也是整个专栏最关键的一篇指引文。文中不仅完整呈现了专栏 9 大核心篇章 + 问答板块的详细目录,更囊括了订阅后必知的核心要点 —— 从阅读设备、实操工具的使用建议,到学习路径、更新规则的清晰说明,再到问题反馈、感悟记录的实用方法,一站式帮你摸清专栏框架、找准学习方向。建议各位订阅者务必认真阅读、吃透内容,这能让你后续的学习更高效、少走弯!

MD Code 1万+

记SpringBoot下载的两种方式

SpringBoot以流形式的下载,以配置文件形式下载

qq_44717657的博客 8942

KCP(快速可靠UDP)——用带宽换延迟的极致艺术

想象你是一个外卖平台的调度员。这就是KCP的本质——

本博客聚焦游戏开发技巧、创业实战心得及大学热门课程干货。这里既有技术深度,也有思维广度,无论你是开发者、创业者还是高校学子,都能在这里找到适合自己的成长之路! 206

Open3D (C++) 点云边界提取【2025最新版】

Compute the boundary points of a point cloud.The implementation is inspired by the PCL implementation. Reference:https://pointclouds.org/documentation/classpcl_1_1_boundary_estimation.html

点云侠的博客 873

Springboot中设置response直接下载文件

需求: 前台点击链接,浏览器直接下载。 1. 后台代码 /** * 下载文件 * * @param response 文件流 * @throws Exception 流异常 */ @ApiModelProperty(value = "下载文件") @GetMapping("downFile") ...

树 6689

FPGA发展趋势:异构计算、AI加速、可重构计算

FPGA技术正朝着异构计算、AI加速和可重构计算三大方向发展。作为高效能计算平台,FPGA在异构架构中与CPU/GPU协同工作,发挥低延迟、高能效优势;在AI领域通过定制化架构实现边缘推理加速;其硬件可重构特性支持动态适应多样化计算需求。最新进展包括部分可重构技术、智能网卡和边缘AI应用。未来,FPGA将在自适应计算、量子接口和软件定义硬件等领域持续突破,成为异构计算架构的核心组件,推动硬件与软件的深度融合。性能对比显示FPGA在能效比(5-20TOPS/W)和灵活性方面具有显著优势。

2301_79143213的博客 970

Springboot文件下载实现和原理分析

Springboot文件下载实现和原理分析 需求 客户端发送请求,可以下载服务端指定文件 无论什么文件,不允许浏览器自动解析,必须作为附件下载 分析 采用springboot实现文件下载,本质上使用的也是javaEE的Servlet+Tomcat技术 下载文件的本质是获取文件的读取流,在服务端需要将文件内容写入到Response的OutputStream中(注意这个写入流不需要flush) 为了防止浏览器解析,需要在响应头中,将文件类型设置为附件。 代码 /** * 文件下载的controller

weixin_42962086的博客 1748

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SpringBoot下载的excel文件,提示部分内容有问题,需要修复

SpringBoot下载的excel文件打开时提示需要修复,如下图: 解决办法:给response的Header设置大小: //加上设置大小 下载下来的excel文件才不会在打开前提示修复 response.addHeader("Content-Length",String.valueOf(file.length())); 完整代码如下: /** * 下载文件 * */ @RequestMapping(val

一个很酷的人 8987

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

SpringBoot如何实现文件上传和下载

文件上传 其实文件上传无非就是文件的读取和写入,明白这个道理之后就好办了。 前端页面 <form method="POST" action="/fileUpload" enctype="multipart/form-data"> <input type="file" id="myFile" name="myFile" /><br/> <in...

wunianisme的博客 1678

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

SpringBoot+Vue下载txt文件

目录 一、前言 二、后端SpringBoot接口V 1.跨域配置 2.Controller接口 三、前端代码 四、测试结果 一、前言 1.SpringBoot需要配置跨域 2.前端使用axios下载txt文件 二、后端SpringBoot接口 1.跨域配置 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; i

阿瑟与非 1615

springboot+vue实现文件上传下载

一、文件上传(基于axios的简单上传) 所使用的技术:axios、springboot、vue; 实现思路:通过h5 :input元素标签进行选择文件,获取所选选择的文件路径,new fromdata对象,设置fromdata的参数,设置axios对应的请求头,最后通过axios发送post请求后端服务。后端服务同过MultipartFile进行文件接收。具体代码如下: 前端代码: 1、创建vu...

qq_22744093的博客 1672

iview Upload组件多文件上传,以及vue文件下载

iview Upload组件多文件上传 系统经常遇到文件上传的问题,iview提供了Upload组建,能够很好的实现文件上传,当然一次上传多个文件也是允许的。 思路:创建一个数组 把需要上传的文件 push到这个数组里面 1.引用组件 2.手动上传,根据官方文档 设置:before-upload ="handleUpload"等于false (1).:before-upload...

dibing0354的博客 1127

java文件下载接口无法识别文件名问题

按照网上的资料,实现一个springboot文件下载接口,调用时出了问题,postman send and save之后,得到的永远是response.json 和 response.bin,无论断点时的文件名是什么,总是下载这个文件名 String fileName = URLEncoder.encode( "your file name", "UTF-8"); httpServletResponse.se

future_xiaowu的博客 4103

Vue + Springboot实现xlsx

网页vue文件index.js - 用于包装请求src/util/request文件 - request进来先运行这个文件的内容。

weixin_45322373的博客 231

springBoot+Vue导出Excel

springBoot+Vue导出Excel 后端下载依赖包: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.

zhouxianglian1的博客 737

springboot 文件下载

org.apache.catalina.connector.ClientAbortException: java.io.IOException: 你的主机中的软件中止了一个已建立的连接。当然,在出现错误时,我在想是不是application/octet-stream的问题,也使用过multipart/form-data,但也是一样的结果。在springboot中,执行如下代码实现文件下载。找了很久的解决方法,但是没有发现什么正确的答案。

m0_74824635的博客 523

介绍一款简单好用Http客户端OkHttp

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一、pandas是什么? 二、使用步骤 1.引入库 2.读入数据 总结 一. 基本的组件 OkHttpClient 它类似于一个浏览器,在应用中应该全局唯一 Request 它表示一次Http请求,可以设置url地址,请求头等信息 RequestBody 它表示http请求体 Response 它表示一次...............

qq1353424111的博客 1562

SpringBoot返回文件让前端下载的几种方式

一定要搞清楚和的区别,如果搞不清楚的,可以和字符流进行映射,,换成这样你就知道读取内容需要使用Reader,写入需要使用Writer了。返回给前端的是输出流,不需要你显示的去返回(),这样会报错。

2509_93929981的博客 399

SpringBoot+vue实现文件下载

后端代码: @RequestMapping("/download/test") public void download(HttpServletResponse response,@RequestBody ProjectHistory projectHistory){ response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition",

风水道人 574
上一篇: jquery 根据年月获取当前月份日列表
下一篇: mysql 使用记录
Carlson_Chis
博客等级 码龄9年 6粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值