前端vue通过URL访问存储在服务器或磁盘的图片

文章介绍了如何在前端使用ElementUI表格展示后端返回的图片URL,以及后端如何配置文件上传路径和拦截器,确保图片访问路径的灵活性。重点讨论了setImgUrl方法和文件存储路径管理的工具类实现。

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

前言

这里前端访问使用的是element

一、前端

说明:

scope.row.img 是后端返回的URL数组

<el-table-column sortable prop="img" label="图片" width="200">

        <template slot-scope="scope">

          <el-image style="width: 100px; height: 100px" :src="setImgUrl(scope.row)"  :preview-src-list="scope.row.img"></el-image>

        </template>

      </el-table-column>

--------------------------------------------------------------------

setImgUrl方法

/设置产品第一张图片

    setImgUrl(row) {

      if(row.img.length != 0) {

        return row.img[0]

      }else {

        return ""

      }

    }

二、后端 

1.配置文件

#文件上传保存路径
file.path.localPath=D:/Admind/java/project/crm/src/main/resources/images/

2.拦截器配置

注意:如果配置有其他的拦截器,一定要排除“/images/**”路径,不要拦截它

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Value("${file.path.localPath}")
private String path;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //图片访问
    registry.addResourceHandler("/" + FileUtils.getPathLastName(path) + "/**").addResourceLocations("file:" + path + "/");
}

}

 FileUtils工具类

工具类调用getPathLastName方法的目的是获取路径的最后一个目录名,作用是:配置文件存储图片的path的路径修改的时候,也同样能够访问得到,不用我们去到代码中进行修改,降低了冗余度。

public class FileUtils {
/**
 * 获取文件路径最后的名
 * @return
 */
public static String  getPathLastName(String path) {
    int i = path.lastIndexOf("/") + 1;
    return path.substring(i);
}

}

 3.访问效果

我的图片存在位置:

### 实现图片存储与显示的方法 #### Django 后端配置 为了在Django项目中处理图像上传并将其保存至MySQL数据库,需先安装`Pillow`库来支持图像文件的操作。可以通过命令行执行 `pip install Pillow` 完成安装。 接着,在模型定义里引入`ImageField`字段用于表示要存储图片路径: ```python from django.db import models class UserProfile(models.Model): avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) ``` 上述代码片段表明每个用户的个人资料可以关联一张头像图片[^1]。 对于数据库连接设置方面,则按照给定的方式修改`settings.py`内的`DATABASES`字典项以适配MySQL环境[^3]。 当涉及到实际的数据迁移操作时,应确保已成功创建相应的表格结构以便后续能够正常存取数据记录。这一步骤可通过运行`python manage.py makemigrations` 和 `python manage.py migrate` 来完成。 #### API接口设计 为了让前端能顺利发送请求并将图片提交给服务器,需要编写视图函数负责接收HTTP POST请求,并调用序列化器验证传入的数据合法性之后再保存实例对象到数据库中去。这里给出一个简单的例子作为参考: ```python from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer from .models import UserProfile class UploadImageView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) ``` 此段程序展示了如何基于RESTful风格构建适合移动端网页使用的API服务端点。 #### Vue 前端实现 在Vue组件内部,使用HTML `<input type="file">`标签允许用户选取本地磁盘上的文件;随后借助Axios发起异步POST请求向指定URL地址传送所选文件的内容流形式。下面是一份简化版的模板代码样例: ```html <template> <div id="app"> <!-- 文件输入框 --> <input @change="onFileChange" type="file"/> <!-- 显示预览图 --> <img v-if="imageSrc" :src="imageSrc" alt="Preview Image"/> </div> </template> <script> import axios from 'axios'; export default { name: 'App', data() { return { imageSrc: '' } }, methods:{ onFileChange(e){ const file = e.target.files[0]; let formData = new FormData(); formData.append('avatar', file); axios.post('/api/upload-image/', formData,{ headers: {'Content-Type': 'multipart/form-data'} }).then(response => { console.log(response); // 更新页面上显示的图片源链接 this.imageSrc = response.data.avatar; }); } } } </script> ``` 这段脚本实现了基本的功能——即让用户可以选择想要上传的照片并通过AJAX方式传递给后台进行持久化处理,同时还能即时更新界面上呈现出来的视觉效果。 #### 额外注意事项 考虑到安全性因素,建议对上传文件大小加以限制,并且只接受特定类型的媒体格式(比如JPEG、PNG)。另外还要记得调整Web服务器配置使得静态资源得以正确加载出来供客户端访问
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值