分布式文件系统 SpringBoot+FastDFS+Vue.js【二】
- 六、实现上传功能并展示数据
- 6.1.创建数据库
- 6.2.创建spring boot项目fastDFS-java
- 6.3.引入依赖
- 6.3.fastdfs-client配置文件
- 6.4.跨域配置GlobalCrosConfig.java
- 6.5.创建模型--实体类
- 6.5.1.FastDfsFile.java
- 6.5.2.FastDfsFileType.java
- 6.5.3.PageBean.java
- 6.5.4.R.java
- 6.5.5.Result.java
- 6.6.创建application.yml
- 6.7.创建Service
- 6.7.1.FastDfsFileService
- 6.7.2.FastDfsFileServiceImpl
- 6.7.3.FastDfsFileTypeService
- 6.7.4.FastDfsFileTypeServiceImpl
- 6.8.创建Mapper
- 6.8.1.FastDfsFileMapper
- 6.8.2.FastDfsFileMapper.xml
- 6.8.3.FastDfsFileTypeMapper
- 6.8.4.FastDfsFileTypeMapper.xml
- 6.9.创建fastDFS客户端
- 6.10.创建全局异常处理器
- 6.11.创建Controller
- 6.13.创建vue2项目
- 6.14.安装相关模块
- 6.15.main.js
- 6.16.src/router/index.js
- 6.17.src/utils/request.js
- 6.18.src/api/fastdfs/fast.js
- 6.19.上传图片页面fastdfsuploadimg.vue
- 6.20.图片管理页面fastdfsimg.vue
- 6.21.效果演示
- endl
六、实现上传功能并展示数据
6.1.创建数据库
CREATE DATABASE IF NOT EXISTS fastdfs CHARACTER SET utf8mb4;show databases;USE fastdfs;CREATE TABLE `fast_dfs_file` (`id` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',`file_id` varchar(200) NOT NULL COMMENT '文件的fileId',`file_path` varchar(200) NOT NULL COMMENT '文件路径',`file_size` bigint(25) NOT NULL COMMENT '文件大小',`file_name` varchar(25) NOT NULL COMMENT '文件名',`ext` varchar(30) NOT NULL COMMENT '文件的扩展名,不包含(.)',`file_type` varchar(50) NOT NULL COMMENT '文件类型',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_time` datetime DEFAULT NULL COMMENT '最后修改时间'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='文件表';CREATE TABLE `fast_dfs_file_type` (`id` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',`file_type` varchar(50) NOT NULL COMMENT '文件类型',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_time` datetime DEFAULT NULL COMMENT '最后修改时间'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='文件类型表';insert into fast_dfs_file_type(file_type)values('image/jpeg'),('image/png'),('image/jpg');
6.2.创建spring boot项目fastDFS-java
6.3.引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.5</version><relativePath/></parent><groupId>com.orange</groupId><artifactId>fastDFS-java</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><!--web起步依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--fastdfs-client-java依赖需要自己手动打包上传到本地仓库--><dependency><groupId>org.csource</groupId><artifactId>fastdfs-client-java</artifactId><version>1.31-SNAPSHOT</version></dependency><!--mybatis起步依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--springboot单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--pagehelper分页插件--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency><!--json处理器--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><!--fastJson是一个JSON的处理工具包,由阿里巴巴公司研发推出。我们使用它将List或者Map转换成JSON对象--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.2.0</version></dependency><!--shiro安全依赖包--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.0</version></dependency></dependencies><build><!--项目打包时会将Java目录中的*.xml文件也进行打包--><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
6.3.fastdfs-client配置文件
## fastdfs-client.properties#fastDFS连接超时时间,针对socket套接字函数connect
connect_timeout_in_seconds = 5
#fastDFS网络超时时间
network_timeout_in_seconds = 30#编码格式
charset = UTF-8#是否启用token验证(针对fdfs配置文件/etc/fdfs/http.conf,防盗链)
http_anti_steal_token = false
#连接密钥(http.conf要配置一样的密钥)
http_secret_key = FastDFS1234567890
#tracker服务器访问端口
http_tracker_http_port = 80#tracker服务器地址,多个以逗号隔开
fastdfs.tracker_servers = 192.168.229.141:22122
6.4.跨域配置GlobalCrosConfig.java
/*** 跨域配置文件**/
@Configuration
public class GlobalCrosConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")// 对所有路径应用跨域配置,所有的当前站点的请求地址,都支持跨域访问。//是否发送Cookie.allowCredentials(true)//放行哪些原始域.allowedHeaders("*").allowedMethods("POST", "GET", "HEAD", "PUT", "OPTIONS", "DELETE").allowedOriginPatterns("*")// 所有的外部域都可跨域访问。// 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名.maxAge(3600);// 超时时长设置为1小时。 时间单位是秒。}
}/*
@Configuration
public class GlobalCrosConfig {@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") //添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置//.allowedOrigins("*") //开放哪些ip、端口、域名的访问权限.allowedOriginPatterns("*") //开放哪些ip、端口、域名的访问权限.allowCredentials(true) //是否允许发送Cookie信息.allowedMethods("GET", "POST", "PUT", "DELETE") //开放哪些Http方法,允许跨域访问.allowedHeaders("*") //允许HTTP请求中的携带哪些Header信息.exposedHeaders("*"); //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)}};}
}*/
6.5.创建模型–实体类
6.5.1.FastDfsFile.java
/*** 文件类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Repository
public class FastDfsFile {private Long id;private String fileId;//文件的fileIdprivate String filePath;//文件路径private Long fileSize;//文件大小private String fileName;//文件名private String ext;//文件的扩展名,不包含(.)private String fileType;//文件类型private LocalDateTime createTime; //创建时间private LocalDateTime updateTime; //修改时间
}
6.5.2.FastDfsFileType.java
/*** 文件类型表*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Repository
public class FastDfsFileType {private Long id;private String fileType;//文件类型private LocalDateTime createTime; //创建时间private LocalDateTime updateTime; //修改时间
}
6.5.3.PageBean.java
/*** 分页查询结果的封装类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean<T> {//当前页数private int currPageNo;//每页显示的记录数private int pageSize;//总记录数private int totalCount;//总页数=总条数/每页显示的条数private int totalPage;//每页的显示的数据private List<T> lists;
}
6.5.4.R.java
@Data
@Accessors(chain = true) //对R进行链式操作
public class R {private Integer code;//响应码private String message;//响应消息private Map<String,Object> data=new HashMap<>();public static R ok(){R r = new R();r.setCode(0);r.setMessage("成功");return r;}public static R error(){R r = new R();r.setCode(-1);r.setMessage("失败");return r;}public R data(String key,Object value){this.data.put(key, value);return this;}
}
6.5.5.Result.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {private Integer code;//响应码,1 代表成功; 0 代表失败private String msg; //响应信息 描述字符串private Object data; //返回的数据//增删改 成功响应public static Result success(){return new Result(1,"success",null);}//查询 成功响应public static Result success(Object data){return new Result(1,"success",data);}//失败响应public static Result error(String msg){return new Result(0,msg,null);}
}
6.6.创建application.yml
server:port: 9090#Mybatis配置
mybatis:configuration: #sql日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl#驼峰命名map-underscore-to-camel-case: truemapper-locations: classpath:com/orange/fastdfs/mapper/*.xml#spring事务管理日志
logging:level:org.springframework.jdbc.support.JdbcTransactionManager: debugspring:#数据库连接信息datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.229.141:3306/fastdfs?characterEncoding=utf-8&&useSSL=falseusername: rootpassword: 123456jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8
# 文件上传的配置
# linux临时文件目录
# mkdir -p /data/tmp/updatefileservlet:multipart:location: /data/tmp/updatefilemax-file-size: 10MBmax-request-size: 10MB
6.7.创建Service
6.7.1.FastDfsFileService
public interface FastDfsFileService {void save(FastDfsFile fastDfsFile);void updateById(FastDfsFile fastDfsFile);FastDfsFile selectById(Long id);Long selectByFileId(String fileId);int deleteFastDfsFileById(Long id);List<FastDfsFile> selectAll();PageBean<FastDfsFile> findFastDfsFileByPage(int currPageNo, int pageSize);
}
6.7.2.FastDfsFileServiceImpl
@Service
public class FastDfsFileServiceImpl implements FastDfsFileService {@Resourceprivate FastDfsFileMapper fastDfsFileMapper;/*** 存储数据** @param fastDfsFile*/@Overridepublic void save(FastDfsFile fastDfsFile) {fastDfsFileMapper.insert(fastDfsFile);}@Overridepublic void updateById(FastDfsFile fastDfsFile) {fastDfsFileMapper.updateById(fastDfsFile);}@Overridepublic FastDfsFile selectById(Long id) {return fastDfsFileMapper.selectById(id);}/*** 根据fileId查询id** @param fileId* @return*/@Overridepublic Long selectByFileId(String fileId) {return fastDfsFileMapper.selectByFileId(fileId);}/*** 根据id删除** @param id* @return*/@Overridepublic int deleteFastDfsFileById(Long id) {return fastDfsFileMapper.deleteById(id);}/*** 查询所有** @return*/@Overridepublic List<FastDfsFile> selectAll() {return fastDfsFileMapper.selectAll();}@Overridepublic PageBean<FastDfsFile> findFastDfsFileByPage(int currPageNo, int pageSize) {PageBean<FastDfsFile> pageBean = new PageBean<>();//封装当前页数pageBean.setCurrPageNo(currPageNo);//每页显示的条数pageBean.setPageSize(pageSize);//总记录数int totalCount = fastDfsFileMapper.selectCount();pageBean.setTotalCount(totalCount);//总页数=总条数/每页显示的条数Double num = Math.ceil(totalCount / pageSize);int totalPage = num.intValue();pageBean.setTotalPage(totalPage);int offset = (currPageNo - 1) * pageSize;int limit = pageBean.getPageSize();//封装每页显示的数据List<FastDfsFile> list = fastDfsFileMapper.findeByPage(offset, limit);pageBean.setLists(list);return pageBean;}
}
6.7.3.FastDfsFileTypeService
public interface FastDfsFileTypeService {int selectByFileType(String fileType);
}
6.7.4.FastDfsFileTypeServiceImpl
@Service
public class FastDfsFileTypeServiceImpl implements FastDfsFileTypeService {@Resourceprivate FastDfsFileTypeMapper fastDfsFileTypeMapper;@Overridepublic int selectByFileType(String fileType) {return fastDfsFileTypeMapper.select(fileType);}
}
6.8.创建Mapper
6.8.1.FastDfsFileMapper
@Mapper
public interface FastDfsFileMapper {void insert(FastDfsFile fastDfsFile);Long selectByFileId(String fileId);int deleteById(Long id);List<FastDfsFile> selectAll();int selectCount();List<FastDfsFile> findeByPage(int offset, int limit);void updateById(FastDfsFile fastDfsFile);FastDfsFile selectById(Long id);
}
6.8.2.FastDfsFileMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.orange.fastdfsjava.mapper.FastDfsFileMapper"><insert id="insert" parameterType="com.orange.fastdfsjava.pojo.FastDfsFile">insert into fast_dfs_file(file_id, file_path, file_size, ext, file_name, file_type, create_time, update_time)values (#{fileId}, #{filePath}, #{fileSize}, #{ext}, #{fileName}, #{fileType}, #{createTime}, #{updateTime})</insert><update id="updateById">update fast_dfs_fileset file_id = #{fileId},file_path = #{filePath},file_size = #{fileSize},ext = #{ext},file_name = #{fileName},file_type = #{fileType},create_time = #{createTime},update_time = #{updateTime}where id = #{id}</update><delete id="deleteById">deletefrom fast_dfs_filewhere id = #{id}</delete><select id="selectByFileId" resultType="java.lang.Long">select idfrom fast_dfs_filewhere file_id = #{fileId}</select><select id="selectAll" resultType="com.orange.fastdfsjava.pojo.FastDfsFile">select *from fast_dfs_file</select><select id="selectCount" resultType="java.lang.Integer">select count(*)from fast_dfs_file</select><select id="findeByPage" resultType="com.orange.fastdfsjava.pojo.FastDfsFile">select *from fast_dfs_file limit #{offset},#{limit}</select><select id="selectById" resultType="com.orange.fastdfsjava.pojo.FastDfsFile">select *from fast_dfs_filewhere id = #{id}</select></mapper>
6.8.3.FastDfsFileTypeMapper
@Mapper
public interface FastDfsFileTypeMapper {int select(String fileType);
}
6.8.4.FastDfsFileTypeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.orange.fastdfsjava.mapper.FastDfsFileTypeMapper"><select id="select" resultType="java.lang.Integer">select count(*)from fast_dfs_file_typewhere file_type = #{fileType}</select>
</mapper>
6.9.创建fastDFS客户端
@Slf4j
public class FastDFSClient {static {//加载fastDFS客户端的配置文件try {ClientGlobal.initByProperties("config/fastdfs-client.properties");log.info("network_timeout = {} ms", ClientGlobal.g_network_timeout);log.info("charset= {}", ClientGlobal.g_charset);} catch (IOException e) {e.printStackTrace();} catch (MyException e) {e.printStackTrace();}}/*** 上传文件* @param file* @param fastDFSFile* @return* @throws IOException*/public static FastDfsFile upload(MultipartFile file, FastDfsFile fastDFSFile) throws IOException {byte[] file_buff = null;//把文件转成输入流InputStream inputStream = file.getInputStream();if (inputStream != null) {//获取输入流中可读取的数据大小int len = inputStream.available();//创建足够大的缓冲区file_buff = new byte[len];//一次性把输入流中的数据全都读入到缓冲区file_buff,那file_buff就要足够大,占用内存也会很大inputStream.read(file_buff);}//关闭输入流inputStream.close();//通过fastDSF的client代码访问tracker和storagetry {//创建tracker的客户端TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());//通过TrackerClient对象获取TrackerServer信息TrackerServer trackerServer = trackerClient.getTrackerServer();StorageServer storageServer = null;//定义storage的客户端,建立与Storage服务器的连接StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);//文件元信息NameValuePair[] metaList = new NameValuePair[1];metaList[0] = new NameValuePair("fileName", fastDFSFile.getFileName());//执行上传String fileId = storageClient.upload_file1(file_buff, fastDFSFile.getExt(), metaList);log.info("upload success. file id is: {}", fileId);fastDFSFile.setFileId(fileId);fastDFSFile.setFilePath(fileId);fastDFSFile.setFileSize(file.getSize());fastDFSFile.setCreateTime(LocalDateTime.now());fastDFSFile.setUpdateTime(LocalDateTime.now());//通过调用service及dao将文件的路径存储到数据库中//关闭storage客户端storageClient.close();return fastDFSFile;} catch (Exception e) {log.error("上传文件失败:", e);e.printStackTrace();return null;}}}
6.10.创建全局异常处理器
/*** 全局异常处理器*/
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class) //捕获所有的异常public Result ex(Exception ex){ex.printStackTrace();return Result.error("对不起,操作失败,请联系管理员");}}
6.11.创建Controller
@Slf4j
@RestController
@RequestMapping("/fastDFSFile")
public class FileServerController {@Resourceprivate FastDfsFileService fastDfsFileService;@Resourceprivate FastDfsFileTypeService fastDfsFileTypeService;@PostMapping("/upload")@ResponseBodypublic R upload(@RequestParam("file") MultipartFile file) throws IOException {//将文件先存储在web服务器上(本机),在调用fastDFS的client将文件上传到 fastDFS服务器FastDfsFile fastDFSFile = new FastDfsFile();String contentType = file.getContentType();//检验当前文件是否在上述集合中log.info("上传的文件类型为:{}", contentType);int count = fastDfsFileTypeService.selectByFileType(contentType);if (count < 1) {log.info("不支持此文件类型上传 : {}", contentType);return R.error().setCode(208).setMessage("不支持此文件类型上传 : " + contentType);}log.info("此文件类型为 : {}", contentType);fastDFSFile.setFileType(contentType);//文件原始名称String originalFilename = file.getOriginalFilename();log.info("原始文件名称 : {}", originalFilename);fastDFSFile.setFileName(originalFilename);//文件扩展名比如22.jpgString filenameExtension = StringUtils.getFilenameExtension(originalFilename);log.info("文件类型 = {}", filenameExtension);//jpgif (filenameExtension == null) {return R.error().setCode(208).setMessage("此文件没有文件扩展名");}fastDFSFile.setExt(filenameExtension);//新文件名称String fileName = UUID.randomUUID().toString().replace("-", "") + "." + filenameExtension;log.info("新文件名称 = {}", fileName);FastDfsFile fastDfsFile1 = FastDFSClient.upload(file, fastDFSFile);if (fastDfsFile1 != null) {fastDfsFileService.save(fastDfsFile1);Long id = fastDfsFileService.selectByFileId(fastDfsFile1.getFileId());fastDfsFile1.setId(id);return R.ok().setCode(200).setMessage("上传成功").data("fastDfsFile",fastDfsFile1);}return R.error().setCode(208).setMessage("上传失败");}@GetMapping("/getPageFastImg/{page}/{limit}")public R getPageFastImg(@PathVariable int page, @PathVariable int limit) {PageBean<FastDfsFile> pageBean = fastDfsFileService.findFastDfsFileByPage(page, limit);return R.ok().setCode(200).setMessage("查询成功").data("pageBean",pageBean);}
}
6.13.创建vue2项目
6.14.安装相关模块
npm install axios@1.5.0
npm install vue-axios
npm install vue-router@3.0.1
npm i element-ui -S
6.15.main.js
import App from './App.vue'
//引入Vue
import Vue from 'vue'
//引入axios
import axios from 'axios'
//引入VueAxios
//安装VueAxios模块后,不需要在每个组件中单独导入axios,只需将axios请求改为this.axios
import VueAxios from 'vue-axios'
//引入VueRouter
import VueRouter from 'vue-router'
//完整引入
//引入ElementUI组件库
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//新建一个router文件夹,在文件夹下新建一个index.js文件
//引入路由器
import router from './router/index'//把axios挂载到vue上
Vue.prototype.$axios = axios;
//使用Vue.use来注册安装插件
Vue.use(VueRouter)
Vue.use(router)
Vue.use(VueAxios, axios)
//使用ElementUI组件库
Vue.use(ElementUI)
//关闭Vue的生产提示
Vue.config.productionTip = false// 创建和挂载根实例
new Vue({router, //将路由器注入到new Vue实例中,建立关联render: h => h(App), //将App组件放入容器中data: {// 空的实例放到根组件下,所有的子组件都能调用Bus: new Vue()}
}).$mount('#app');
6.16.src/router/index.js
//在路由文件router/index.js中配置
// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";//引入组件
import fastdfsuploadimg from '../view/fastdfs/fastdfsuploadimg'//上传页
import fastdfsimg from "../view/fastdfs/fastdfsimg"//创建路由
const routes = [//定义路由{path: '/',name: 'fastdfsuploadimg',component: fastdfsuploadimg},{path: '/fastdfsimg',name: 'fastdfsimg',component: fastdfsimg},
]//创建并暴露一个路由器
const router = new VueRouter({mode: 'history',base: process.env.BASE_URL,routes
})export default router
6.17.src/utils/request.js
import axios from 'axios'// 创建axios实例
const service = axios.create({baseURL: 'http://localhost:9090', // api 的 base_urltimeout: 1000000 // 请求超时时间
})// http request 拦截器
// 请求拦截器
service.interceptors.request.use(config => {// 可以在这里添加请求头等信息return config;},error => {// 请求错误处理console.log(error);return Promise.reject(error);}
);// http response 拦截器
// 响应拦截器
service.interceptors.response.use(response => {// 对响应数据做处理,例如只返回data部分const data = response.data;return data;},error => {// 响应错误处理console.log('err' + error); // for debugreturn Promise.reject(error);}
);export default service;
6.18.src/api/fastdfs/fast.js
import request from "../../utils/request";const api_name = '/fastDFSFile'export default {//上传图片uploadImg() {return request({url: `${api_name}/upload`,method: 'post',})},getPageFastImg(page, limit) {return request({url: `${api_name}/getPageFastImg/${page}/${limit}`,method: 'get',})},
}
6.19.上传图片页面fastdfsuploadimg.vue
<template><div><h2>上传图片</h2><el-form><el-form-item><el-uploadlist-type="picture-card":multiple="false":action="uploadUrl":limit="1":on-success="onUploadSuccessIdCard"><i class="el-icon-plus"></i></el-upload></el-form-item></el-form><span v-if="dialogImageUrl != ''">图片地址:<a target="_blank" v-if="dialogImageUrl != ''" :href="dialogImageUrl">{{ dialogImageUrl }}</a></span><br/></div>
</template><script>
export default {name: "UploadImg",data() {return {dialogImageUrl: "",file_id: "",dialogVisible: false,uploadUrl: "http://localhost:9090/fastDFSFile/upload", //文件上传地址datas: {},};},methods: {onUploadSuccessIdCard(response) {this.file_id = response.data.fastDfsFile.fileId;this.datas = response.fastDfsFile.data;this.dialogImageUrl = "http://192.168.229.141/" + response.data.fastDfsFile.filePath;},},
};
</script><style scoped>
</style>
6.20.图片管理页面fastdfsimg.vue
<template><div><h2>图片管理</h2><!--图片列表--><el-tablesize="small"style="margin: 30px;"empty-text="无数据":data="imgList"highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"><el-table-column align="center" sortable prop="filePath" label="文件路径" width="450"></el-table-column><el-table-column align="center" sortable prop="fileSize" label="文件大小" width="100"></el-table-column><el-table-column align="center" sortable prop="fileName" label="文件名" width="130"></el-table-column><el-table-column align="center" sortable prop="ext" label="扩展名" width="100"></el-table-column><el-table-column align="center" sortable prop="fileType" label="文件类型" width="100"></el-table-column><el-table-column align="center" sortable prop="filePath" label="预览图片" width="100"><template slot-scope="scope"><img :src="getImageUrl(scope.row.filePath)" style="max-width: 100px;max-height: 100px" alt="图标"/></template></el-table-column></el-table><!-- 分页 --><el-pagination class="pagination" style="text-align: center;margin-top: 50px"layout="prev, pager, next":current-page="page":total="total":page-size="limit"></el-pagination></div>
</template><script>
import fastApi from "@/api/fastdfs/fast";export default {name: "FastdfsImg",data() {return {total: 0, // 数据库中的总记录数page: 1, // 默认页码limit: 5, // 每页记录数imgList: {},baseImagePath: 'http://192.168.229.141/', // 图片的基础路径}},created() {this.init()},methods: {init() {fastApi.getPageFastImg(this.page, this.limit).then(response => {this.imgList = response.data.pageBean.liststhis.total = response.data.pageBean.totalCount})},getImageUrl(filePath) {return `${this.baseImagePath}${filePath}`; // 拼接图片路径},},
}
</script><style scoped></style>
6.21.效果演示