spring boot+html访问图片

本文介绍了解决前端项目中图片无法加载的问题。通过在配置文件中正确设置静态资源路径,最终成功显示图片。适用于使用不同开发工具及配置文件格式的开发者。

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

刚开始接触时,总是提示无法载入图片,百度尝试过很多解决办法,一般都是修改配置文件指定一下静态资源路径,例如在配置文件加入:
spring.resources.static-locations=‘静态资源路径’

但我有点不一样,可能是因为开发工具版本不一样,我在application.yml配置文件中,加入类似代码:

spring:
  web:
    resources:
      static-locations: classpath:/

在这里插入图片描述
看一下我的图片目录:
在这里插入图片描述
login.html页面:
在这里插入图片描述

然后访问页面:
在这里插入图片描述图片就出来啦

### 使用 Spring Boot 和 Vue 实现图片上传功能 #### 后端部分 (Spring Boot) 为了实现跨域资源共享,在控制器上添加 `@CrossOrigin` 注解可以解决前端与后端之间的跨域访问问题[^2]。 创建一个用于处理文件上传的接口: ```java import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/api/files") public class FileUploadController { @PostMapping("/upload") @CrossOrigin(origins = "http://localhost:8080") // 假设Vue应用运行在该地址 public String uploadFile(@RequestParam("file") MultipartFile file) { if(file.isEmpty()) { return "Failed to upload empty file."; } try { byte[] bytes = file.getBytes(); // 存储逻辑,比如保存到本地磁盘或云存储 return "Successfully uploaded!"; } catch(Exception e){ return "Error occurred while uploading the file"; } } } ``` 这段代码定义了一个简单的 RESTful API 来接收来自客户端的文件并将其保存下来。这里假设只做基本测试而不涉及复杂的业务逻辑和安全性考虑。 #### 前端部分 (Vue.js) 构建表单组件来允许用户选择要上传的照片,并调用上述服务完成提交操作: ```html <template> <div id="app"> <h1>Image Upload</h1> <!-- 文件输入框 --> <input type="file" ref="fileInput" v-on:change="handleFileChange"/> <!-- 提交按钮 --> <button @click="submit">Submit</button> {{ message }} </div> </template> <script> export default { data(){ return{ selectedFile:null, message:'' }; }, methods:{ handleFileChange(event){ this.selectedFile=event.target.files[0]; }, async submit(){ const formData=new FormData(); formData.append('file',this.selectedFile); await fetch('http://localhost:8081/api/files/upload',{ method:"POST", body:formData }).then(response=>response.text()) .then(data=>{ this.message=data; }); } } }; </script> ``` 在这个例子中,当用户选择了图像并通过点击“Submit”触发事件时,会将选中的文件封装成 `FormData` 对象发送给服务器进行处理。最后更新视图显示返回的消息状态。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值