feat[后台管理]:图片的预览和下载功能

This commit is contained in:
2025-02-13 14:25:23 +08:00
parent 27c18a19c5
commit 62c372c456
21 changed files with 292 additions and 18 deletions
@@ -6,6 +6,7 @@ import com.central.common.model.Result;
import com.central.file.service.IFileService;
import com.central.file.utils.HexToJpeg;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
@@ -81,11 +82,16 @@ public class FileController {
return fileService.getViewUrl(id);
}
@PostMapping("/files/name")
public String getViewUrlByName(@RequestBody String name) {
@GetMapping("/files/name")
public String getViewUrlByName(@RequestParam String name) {
return fileService.getViewUrlByName(name);
}
@GetMapping("/files/name/style")
public String getViewUrlByNameStyle(@RequestParam Map<String, Object> params) {
return fileService.getZipViewUrlByName(MapUtils.getString(params,"name"),MapUtils.getString(params, "style"));
}
@GetMapping("/type/{id}")
public String getFileInfo(@PathVariable String id) {
FileInfo fileInfo = fileService.getFileInfo(id);
@@ -29,6 +29,8 @@ public interface IFileService extends IService<FileInfo> {
String getViewUrlByName(String name);
String getZipViewUrlByName(String name, String style);
FileInfo getFileInfo(String id);
FileInfo createFile(String path);
@@ -54,6 +54,11 @@ public class CosService extends AbstractIFileService {
return "";
}
@Override
public String getZipViewUrlByName(String name, String style) {
return "";
}
@Override
public void out(String id, OutputStream os) {
FileInfo fileInfo = baseMapper.selectById(id);
@@ -50,6 +50,11 @@ public class FastdfsService extends AbstractIFileService {
return "";
}
@Override
public String getZipViewUrlByName(String name, String style) {
return "";
}
@Override
public void out(String id, OutputStream os) {
}
@@ -80,6 +80,11 @@ public class OssService extends AbstractIFileService {
}
@Override
public String getZipViewUrlByName(String name, String style) {
return ossTemplate.getViewUrl(name,style);
}
@Override
public FileInfo getFileInfo(String id) {
return baseMapper.findById(id);
@@ -55,6 +55,11 @@ public class S3Service extends AbstractIFileService {
return "";
}
@Override
public String getZipViewUrlByName(String name, String style) {
return "";
}
@Override
public void out(String id, OutputStream os) {
FileInfo fileInfo = baseMapper.selectById(id);
@@ -1,6 +1,8 @@
package com.central.order.controller;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.LoginAppUser;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
@@ -74,12 +76,15 @@ public class OrderController {
@Autowired
private TencentPayProperties tencentPayProperties;
@Value("${cdn.oss-url}")
@Value("${file.oss-url}")
private String cdnOssUrl;
@Value("${cdn.url}")
@Value("${file.cdn-url}")
private String cdnUrl;
@Value("${file.style}")
private String fileStyle;
/**
* 列表
*/
@@ -125,11 +130,13 @@ public class OrderController {
params.put("userId", user.getId());
// 获取当前日期,格式化为 yyyyMMdd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATEMINUTE_FORMAT);
PageResult<Order> result = orderService.findListByUser(params);
if (result.getCount() > 0){
List<Map> page = new ArrayList<>();
Map<String, String> fileMap = new HashMap<>();
fileMap.put("style", fileStyle);
for(Order order : result.getData()){
Map<String,Object> orderFileMap = new HashMap<>();
orderFileMap.put("time", sdf.format(order.getCreateTime()));
@@ -143,6 +150,9 @@ public class OrderController {
String url = fileCenterService.getViewUrlByName(orderFile.getFilePath());
imgMap.put("url", url.replace(cdnOssUrl,cdnUrl));
imgMap.put("contentType", ContentTypeUtil.getContentTypeFromUrl(url));
fileMap.put("name",orderFile.getFilePath());
imgMap.put("viewUrl", fileCenterService.getViewUrlByNameStyle(fileMap));
resultList.add(imgMap);
}
}
@@ -167,9 +177,13 @@ public class OrderController {
public Result<Order> createOrder(@RequestBody Order order) {
LoginAppUser user = LoginUserContextHolder.getUser();
//@TODO 设置价格逻辑优化
order.setOrderAmount("1990");
order.setUserId(user.getId());
order.setTenantId(TenantContextHolder.getTenant());
//景区唯一二维码codeId,该二维码中包含价格信息
if (order.getCodeId() == null){
order.setCodeId("f83be3a9-2888-4000-8cf9-e6acdb3a22cd");
}
@@ -18,9 +18,11 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -46,6 +48,9 @@ public class OrderFileController {
@Autowired
private IOrderService orderService;
@Value("${file.style}")
private String fileStyle;
/**
* 列表
*/
@@ -56,7 +61,17 @@ public class OrderFileController {
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return orderFileService.findList(params);
PageResult<OrderFile> pageResult = orderFileService.findList(params);
Map<String, String> fileMap = new HashMap<>();
fileMap.put("style", fileStyle);
if (pageResult.getResp_code() == 0){
for (OrderFile orderFile: pageResult.getData()){
orderFile.setViewUrl(fileCenterService.getViewUrlByName(orderFile.getFilePath()));
fileMap.put("name", orderFile.getFilePath());
orderFile.setZipViewUrl(fileCenterService.getViewUrlByNameStyle(fileMap));
}
}
return pageResult;
}
/**
@@ -5,10 +5,7 @@ import com.central.common.model.FileInfo;
import com.central.common.model.Result;
import com.central.order.feign.fallback.FileCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@@ -41,6 +38,9 @@ public interface FileCenterService {
@PostMapping("/path")
FileInfo creatFileInfo(@RequestBody String path);
@PostMapping("/files/name")
String getViewUrlByName(@RequestBody String name) ;
@GetMapping("/files/name")
String getViewUrlByName(@RequestParam("name") String name) ;
@GetMapping("/files/name/style")
String getViewUrlByNameStyle(@RequestParam("params") Map<String,String> params) ;
}
@@ -50,6 +50,11 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
return "";
}
@Override
public String getViewUrlByNameStyle(Map<String, String> params) {
return "";
}
};
}
}
@@ -29,6 +29,9 @@ public class OrderFile extends SuperEntity {
private Long userId;
private transient String viewUrl;
//文件缩略图
private transient String zipViewUrl;
// 景区ID
private Long tourismId;
@@ -42,9 +42,10 @@ tencent:
appSecret: ${zlt.security.tencent.app-secret}
accessTokenUrl: ${zlt.security.tencent.accessTokenUrl}
getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token=
cdn:
file:
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
url: cdn.goflytec.com
cdn-url: cdn.goflytec.com
style: image/resize,m_fixed,w_100,h_90
#审计日志
# audit-log:
# enabled: true
@@ -94,6 +94,7 @@ public interface CommonConstant {
*/
String MONTH_FORMAT = "yyyy-MM";
String DATE_FORMAT = "yyyy-MM-dd";
String DATEMINUTE_FORMAT = "yyyy-MM-dd HH:mm";
String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
String SIMPLE_MONTH_FORMAT = "yyyyMM";
String SIMPLE_DATE_FORMAT = "yyyyMMdd";
@@ -1,7 +1,9 @@
package com.central.oss.template;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
@@ -134,6 +136,24 @@ public class OssTemplate implements InitializingBean {
return url.toString();
}
/**
* 获取缩略图预览地址
* @param objectName 对象名
* @return
*/
public String getViewUrl(String objectName,String style) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 7);
if (style == null) {
style = "image/resize,m_fixed,w_100,h_90"; // 默认缩略图样式
}
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(fileProperties.getOss().getBucketName(), objectName, HttpMethod.GET);
req.setProcess(style);
req.setExpiration(cal.getTime());
URL url = ossClient.generatePresignedUrl(req);
return url.toString();
}
/**
* 获取预览地址
* @param objectName 对象名
@@ -61,6 +61,10 @@
{
path: '/orders/tourism.html',
component: './orders/Tourism',
},
{
path: '/orders/qrcode.html',
component: './orders/Qrcode',
}
],
},
@@ -6,7 +6,7 @@ import {
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, message, Popconfirm } from 'antd';
import { Typography, message, Popconfirm, Tag } from 'antd';
import React, { useRef, useState } from 'react';
const { Link } = Typography;
@@ -30,6 +30,20 @@ const { Link } = Typography;
// }
// };
// 状态颜色映射
const statusColorMap = {
0: { color: 'yellow', text: '待处理' },
1: { color: 'orange', text: '待处理' },
3: { color: 'green', text: '已完成' },
2: { color: 'red', text: '已取消' },
};
// 渲染状态标签
const renderStatus = (status: {} | null | undefined) => {
const statusInfo = statusColorMap[status] || { color: 'gray', text: '未知状态' };
return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
};
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
@@ -49,6 +63,7 @@ const TableList: React.FC = () => {
{
title: '状态',
dataIndex: 'orderStatus',
render: (status) => renderStatus(status),
},
{
title: '创建时间',
@@ -6,7 +6,7 @@ import {
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, message, Popconfirm } from 'antd';
import { Typography, message, Popconfirm, Image } from 'antd';
import React, { useRef, useState } from 'react';
const { Link } = Typography;
@@ -30,6 +30,8 @@ const handleDelete = async (deletefile: ORDERS.OrderFile) => {
}
};
const imagePreviewTypes = ['image/jpeg', 'image/png', 'image/gif']; // 可预览的图片类型
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
@@ -47,8 +49,27 @@ const TableList: React.FC = () => {
dataIndex: 'fileId',
},
{
title: '文件路径',
dataIndex: 'filePath',
title: '文件',
dataIndex: 'zipViewUrl',
render: (zipViewUrl, entity) => (
<>
{imagePreviewTypes.includes(entity.fileType) ? (
<Image src={zipViewUrl} width={100} />
) : (
<Link href={entity.viewUrl} target="_blank" rel="noopener noreferrer">
下载文件
</Link>
)}
<Link
href={entity.viewUrl} // 假设 originalUrl 是原图的 URL
target="_blank"
rel="noopener noreferrer"
style={{ marginLeft: '8px', color: 'blue' }} // 添加样式以区分
>
预览原图
</Link>
</>
),
},
{
title: '文件类型',
@@ -0,0 +1 @@
@import (reference) '~antd/es/style/themes/index';
@@ -0,0 +1,121 @@
import { qrcode } from '@/services/orders/api';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
PageContainer,
ProFormText,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
const { Link } = Typography;
// const handleDelete = async (deletefile: FILES.File) => {
// const hide = message.loading('正在删除');
// try {
// const result = await deleteFile(deletefile.id);
// hide();
// if (result.resp_code === 0) {
// message.success('删除File成功');
// return true;
// } else {
// message.error(result.resp_msg);
// return false;
// }
// } catch (error) {
// hide();
// message.error('删除File失败');
// return false;
// }
// };
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
const columns: ProColumns<ORDERS.Qrcode>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
},
{
title: 'ID',
dataIndex: 'id',
},
{
title: 'CodeID',
dataIndex: 'codeId',
},
{
title: '景区ID',
dataIndex: 'tourismId',
},
{
title: '文件路径',
dataIndex: 'path',
},
{
title: '文件ID',
dataIndex: 'fileId',
},
{
title: '设备SN',
dataIndex: 'deviceSn',
},
{
title: '状态',
dataIndex: 'status',
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
},
{
title: '操作',
key: 'action',
render: (_, entity) => <Popconfirm
title={`确认删除文件[${entity.id}]?`}
onConfirm={async () => {
// const success = await handleDelete(entity);
// if (success) {
// if (actionRef.current) {
// actionRef.current.reload();
// }
// }
}}
>
<Link>删除</Link>
</Popconfirm>,
},
];
return (
<PageContainer header={{ subTitle: '管理任务' }}>
<QueryFilter
defaultCollapsed
split
span={6}
className="query-filter"
onFinish={async (values) => setParams(values)}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
</QueryFilter>
<ProTable<ORDERS.Qrcode>
rowKey="id"
headerTitle="二维码列表"
request={qrcode}
actionRef={actionRef}
columns={columns}
search={false}
params={params}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
}}
/>
</PageContainer>
);
};
export default TableList;
@@ -51,4 +51,13 @@ export async function deleteTourism(id: number) {
method: 'DELETE',
});
return result;
}
export async function qrcode(params?: { [key: string]: string | number }) {
const { current, pageSize, ...rest } = params ?? {};
const result = await request<SYSTEM.Page<ORDERS.Qrcode>>('/api-order/qrcode', {
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: result.data, total: result.count };
}
@@ -17,6 +17,8 @@ declare namespace ORDERS {
userId: string;
fileId: string;
filePath: string;
viewUrl: string;
zipViewUrl: string;
orderNo: string;
fileType: string;
createTime?: string;
@@ -36,4 +38,18 @@ declare namespace ORDERS {
tenantId?: string;
updateTime?: string;
}
type Qrcode = {
id: number;
codeId: string;
tourismId: string;
path: string;
fileId: string;
deviceSn: string;
createTime?: string;
status: number;
tenantId?: string;
updateTime?: string;
}
}