springBoot 连接打包成jar包运行时,获取图片上传文件、前端页面等文件

本文介绍了springBoot项目打包成jar包运行时,如何配置获取图片上传文件和前端页面等静态资源的方法。通过在application.yml中设置配置,解决了文件上传后的访问路径问题,并且在前端文件更新时,无需重启服务器即可生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springBoot 连接打包成jar包运行时,获取图片上传文件、前端页面等文件

问题背景:在使用springboot进行开发时,会将项目打包成jar包,进行运行。
问题1:使用文件上传功能后,怎么获取文件?
问题2:每次更新前端文件,都需要重新运行项目jar包,是否过于麻烦


解决方法

在application.properties/application.yml中进行配置

web.upload-path=d:/myfile/upload
web.front-path=d:/myfile/front
spring.resources.static-locations=file:${web.upload-path},file:${web.front-path}

properties配置方式

web:
  upload-path: d:/myfile/upload
  front-path: d:/myfile/front</
首先,你需要将该jar添加到Spring Boot项目的依赖中。可以在Maven的pom.xml文件中添加以下代码: ```xml <dependency> <groupId>com.example</groupId> <artifactId>my-matlab-app</artifactId> <version>1.0.0</version> </dependency> ``` 其中,`com.example`是你的jar的groupId,`my-matlab-app`是artifactId,`1.0.0`是版本号。 接下来,你可以在你的Spring Boot项目中创建一个Controller接收前端传过来的rgb值,然后调用你的jar中的方法生图片。可以用以下代码实现: ```java @RestController @RequestMapping("/image") public class ImageController { @GetMapping("/{r}/{g}/{b}") public String generateImage(@PathVariable int r, @PathVariable int g, @PathVariable int b) { // 调用你的jar中的方法生图片 // 代码略 // 将生的图片转换Base64编码的字符串 String base64Image = convertImageToBase64(image); // 返回Base64编码的字符串 return base64Image; } private String convertImageToBase64(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { e.printStackTrace(); } byte[] imageBytes = baos.toByteArray(); return Base64.getEncoder().encodeToString(imageBytes); } } ``` 在上面的代码中,我们使用了`@GetMapping`注解来接收前端传过来的rgb值,并将它们作为参数传递给我们的jar中的方法。然后将生的图片转换Base64编码的字符串,并将它返回给前端。 最后,在前端中调用该接口,获取Base64编码的图片,并将它展示在弹窗中。可以用以下代码实现: ```javascript <template> <div> <button @click="showImage">Show Image</button> <div v-if="showPopup"> <div class="popup"> <img :src="image" /> <button @click="closePopup">Close</button> </div> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { showPopup: false, image: null } }, methods: { showImage() { axios.get('/image/255/0/0') .then(response => { this.image = 'data:image/png;base64,' + response.data this.showPopup = true }) }, closePopup() { this.showPopup = false this.image = null } } } </script> <style> .popup { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .popup img { max-width: 80%; max-height: 80%; } </style> ``` 在上面的代码中,我们使用了axios库来调用我们的Controller接口,并将返回的Base64编码的图片展示在弹窗中。当用户点击关闭按钮,弹窗会关闭并清空图片数据。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值