SpringBoot项目通过URL访问本地文件实现方法和遇到的问题

SpringBoot 数据访问与操作教程 Spring Boot是一个快速、敏捷的开发框架,可以轻松用于构建单个、微服务架构或整体应用。它的主要优点之一就是在于提供了自动配置特性,Spring Boot可以自动化很多应用设置,比如数据源的配置、日志系统的选择等。另一个重要的特点是其“约定优于配置”的设计理念,使得开发人员不用再重复编写相同的代码。基于这些特点,它在Java社区中受到广泛关注。在实际项目开发中,我们通常需要对数据库进行读、写操作,并根据业务需求增删改查数据。 阅读详情

场景

当文件上传到服务器后,需要通过URL去访问服务器相应的文件,可以是图片或其他的文件。

实现

由于SpringBoot本质是嵌入的tomcat,所以并不能够直接从tomcat目录去访问需要的资源,因此需要继承WebMvcConfigurer 去实现自己的拦截器,将用于访问的/show/**去映射本地的文件夹地址
此处要注意路径的尾部一定要加上 " / ",也就是文件分隔符,不然是不能够正确映射到相应的文件夹的
也就是file:D:/Demo/和file:D:/Demo的区别,一定要使用前者才能正确访问

package com.hwh.communitymanage.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * @description:
 * @author: HwH
 * @create: 2022-11-24 23:11
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    // 静态资源展示
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // PS:注意文件路径最后的斜杠(文件分隔符),如果缺少了,就不能够正确的映射到相应的目录
        String basePath = "file:D:/Demo/";
      	registry.addResourceHandler("/show/**").addResourceLocations(basePath);
    }

}

测试

完成了上述配置,启动项目,访问目录下的文件
URL地址:localhost:8080/show/1.jpg
显示出图片就说明能够正确访问了
在这里插入图片描述

如果加了Shiro之类的授权验证,需要加到相应的白名单,或者访问的时候携带Token,以便于Shiro校验通过

Java(springboot) 读取txt文本内容代码实例 主要介绍了Java(springboot) 读取txt文本内容代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 立即下载

相关推荐

告别手动拖拽!PyQt5/PyQt6 QTableView列宽自适应窗口的三种实战方案(附性能对比)

本文详细介绍了PyQt5/PyQt6中QTableView列宽自适应窗口的三种实战方案,包括Stretch模式、resizeEvent手动计算和ResizeToContents模式,并附有性能对比。帮助开发者解决窗口大小变化时列宽不变的常见问题,提升用户体验和开发效率。

weixin_42538752的博客 234

springboot对本地文件进行操作

spring boot 读写本地文件 获取本地文件路径

六六的小帅的博客 9942

YOLOv8-seg模型后处理实战:从输出解析到mask生成的完整流程

本文详细解析了YOLOv8-seg实例分割模型的后处理完整流程,从理解output0与output1的双输出结构,到实现检测框的置信度过滤、坐标转换与NMS,再到核心的掩膜生成数学原理与矩阵乘法实现。文章深入探讨了如何将掩膜系数与原型掩膜库结合,生成像素级分割结果,并提供了掩膜上采样、边缘优化、性能提升及解决实际应用难题的实战方案。

xgboost6farmer的博客 318

SpringBoot对静态资源映射的处理

在解决上述问题前,我们来先了解一哈springboot是如何对静态资源的处理。 以下内容仅仅提供个人理解,不确保其正确性!! 1. SpringBoot对静态资源映射的处理 SpringBoot默认为我们提供了静态资源的处理,其通过配置类WebMvcAutoConfiguration实现的。此类存放了与web开发相关的各种配置属性和方法。 1.1 addResourceHandlers()方法 察看WebMvcAutoConfiguration类的源码。在此类中,addResourceHandlers()

菩提小猿的博客 2646

OpenCV透视变换实战:5分钟搞定歪斜证件照矫正(附完整代码)

本文详细介绍了如何使用OpenCV的透视变换技术快速矫正歪斜证件照,包含完整的Python代码实现。通过特征检测、坐标计算和矩阵变换三个核心步骤,5分钟内即可将手机拍摄的歪斜图像自动矫正为专业级证件照,大幅提升图像处理效率。

weixin_29094979的博客 482

LabVIEW新手必看:5分钟搞定S7-1200 OPC通信(附完整配置截图)

本文详细介绍了LabVIEW与西门子S7-1200 PLC通过OPC通信实现工业监控系统的完整配置流程。从环境准备、PLC数据块配置到OPC Server高级设置,逐步指导新手快速建立稳定通信链路,并分享工业级应用的优化技巧和异常处理方案,帮助用户提升自动化系统集成效率。

rl6adventurer的博客 641

Springboot项目访问路径

springboot项目的访问路径查询 创建的springboot项目,启动后,默认的访问路径是主机ip+默认的端口号是8080。如果没有配置默认的index.jsp,则访问显示Whitelabel Error Page。 如果在controller接口用requestMapping配置了请求路径,那么访问路径就是主机+默认端口号+方法的请求路径。如果在controller类上方定义了requestMapping,那么就是主机地址+默认端口号+类上的地址+方法地址去具体访问。 如果修改了端口,则访问路径是i

fglxhlw的博客 1万+

告别硬件!用Wokwi在线模拟ESP32点灯,5分钟搞定开发环境搭建

本文介绍如何使用Wokwi在线模拟器快速搭建ESP32开发环境,5分钟内完成点灯实验。无需硬件即可体验GPIO控制、PWM调光等核心功能,特别适合物联网开发初学者和快速原型验证。Wokwi的零成本、全功能模拟特性让嵌入式开发变得前所未有的简单高效。

weixin_42567497的博客 495

SpringBoot映射URL访问本地文件,实现文件预览功能

由于访问服务器文件的方式不安全,且现在中文文件访问报错解决不了,最终重新写了一个文件下载接口,前端根据返回的文件流进行预览展示。resourceHandler 配置为/files/**,accessFilePath配置为E:/files/。,即可访问到本地磁盘E:/files/下面的同名文件。

我可能在扯淡 2680

RK3566基于Buildroot定制QT开发环境的完整指南

本文详细介绍了如何在RK3566开发板上使用Buildroot定制QT开发环境的完整流程。从基础环境搭建、Buildroot初始配置到QT模块选择与编译验证,提供了实战经验和常见问题解决方案,帮助开发者高效完成嵌入式Linux下的QT开发环境部署。

weixin_26804345的博客 358

为什么Nano Banana在图像一致性上碾压GPT和豆包?深度解析其技术原理与使用技巧

本文深度解析了Nano Banana在图像一致性上超越GPT和豆包等工具的技术原理。它通过基于参考图的强条件生成、精准的区域感知与掩码控制等核心技术,实现了“外科手术式”的精准图像编辑。文章还分享了包括提示词工程、参数调整在内的实用技巧,并探讨了通过API Key将其能力集成到自动化工作流中的潜力。

omega的博客 357

SpringBoot项目中前端页面通过URL访问本地文件夹(访问静态文件)

文章目录前端页面通过URL访问本地文件夹在application.yml中添加配置实现WebMvcConfigurer接口前端页面中进行访问 前端页面通过URL访问本地文件夹 因为SpringBoot项目中使用的嵌入Tomcat,所以前端页面不能像以前那样直接将从Tomcat很目录访问文件。 解决办法:继承WebMvcConfigurer接口对访问URL进行拦截,然后将访问文件的URL映射至本地文件夹 在application.yml中添加配置 首先在本地创建文件夹 accessFile: reso

渣渣瑞 1万+

SBM与超效率SBM模型实战:从原始面板数据到MATLAB高效实现

本文详细介绍了SBM模型与超效率SBM模型的核心原理,并提供了从原始面板数据预处理到MATLAB高效实现的完整实战指南。通过具体代码解析,帮助研究者掌握如何利用MATLAB进行数据标准化、模型构建、效率求解及结果可视化,从而精准评估决策单元的相对效率,尤其适用于在高效单元中进一步精细排名的场景。

weixin_29100399的博客 480

SpringBoot映射本地文件到URL路径

需要一个配置类,实现了WebMvcConfigurer接口 import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframewo

约定喵 3118

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

深度学习工具包 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通过url直接访问项目内的图片

Spring Boot通过url直接访问项目内的图片 1、在配置文件中配置相应路径 在application.yml中添加: spring: mvc: static-path-pattern: /** 或者在application.properties中添加: spring.mvc.static-path-pattern=/** 2、加入图片 将图片放入{项目名}/src/main/resources/static目录下。 如下图中目录下的test.jpg文件 3、通过url访问 在浏览器

KIIOU的博客 4141

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

SpringBoot将图片以URL的形式访问

在项目中我们难免会遇到访问图片,但是又不能出现存放图片具体的盘符,正好最近做产品时遇到这种场景,将以URL的形式访问图片的方法分享给进来的朋友们! SpringBoot处理这种形式,非常简单,只需要简单的几步配置就可以了! 第一步:在properties文件配置图片存放路劲 这里我以我实际项目中的路劲演示 server.resource=C:/behavior/ #上传图片文件地址...

打酱油的程序员 3317

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

springboot项目通过URL访问静态图片,本地文件夹下的图片!

听说有的人看文章不关注,还有的人不点赞? Springboot读取本地图片并显示 方法一 如果文件不多的话可以考虑将图片放到项目的静态文件夹中 在配置文件里加上 spring.mvc.static-path-pattern= /** 表示静态资源访问的格式 配置好之后启动程序,在地址栏中访问 localhost:8080/images/1.png 可以展示! 方法二 如果图片多的话就不可能一张一张的往里面放了! 所以下面还有一条命令! spring.resources.static-locations

Lang_Ren_g的博客 2万+

SpringBoot获取项目所有url路径和方法名

SpringBoot获取项目所有url路径和方法名 需求:在启动SpringBoot项目时查询出所有url路径和方法名存储到数据库表中 答案: 1.注入ConfigurableApplicationContext @Autowired ConfigurableApplicationContext run; 2.获取项目所有url,并生成sql //获取项目所有url public...

weixin_45074679的博客 9690

springboot通过url访问本地文件

启动服务后在浏览器输入url,访问本地的文件——图片、TXT文件··· @Configuration public class MyWebMvcConfigurer extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 访问路径

普通还不自信的程序员 2448

SpringBoot项目启动后访问404

1.环境 jdk 1.8,开发工具:idea 写了一个controller的demo,正常启动后,访问发现404. 如图所示. 通过postman使用url访问发现返回404,如图: 通过浏览器用localhost + 端口访问报404. 检查: 1.检查发现项目启动后没有项目路径,同时端口没有错误. 2.路径url没有拼写错误, url为路径类路径加方法路径. 3.url使用的注解没有错误...

weixin_41276238的博客 3万+

SpringBoot上传文件到本地 配置项目访问路径URL的根路径,访问项目本地图片

SpringBoot配置项目访问路径URL的根路径,并访问项目本地图片

m0_46598549的博客 2818

spring boot映射本地文件,前端url访问

springboot映射本地文件 上代码 @Configuration public class WebMvcConfig implements WebMvcConfigurer { //静态资源映射 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //把本地静态资源映射到项目 try { registry.addR

qq_43536071的博客 3559

springboot通过url访问项目外的其他目录下的资源

第一种方式、在配置文件application.properties,添加配置 资源映射地址为file:D://User/,图片存放的真实路径 spring.resources.static-locations=file:D://User/ 资源映射路径为/image/**,你想在url访问的请求路径 spring.mvc.static-path-pattern=/image/** 第二种方式、在代码上添加配置项文件 import org.springframework.context.annotation.

各自安好、的博客 2924

【web】springboot3 生成本地文件 url

【web】springboot3 生成本地文件 url。

m0_52733659的博客 1488
上一篇: 跨域的原因和解决
下一篇: Charles在Mac上对Android抓包
DespairC
博客等级 码龄7年 25粉丝 28原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值