feat[通用模块]:getViewUrlByName在文件存储中fileName,小程序二维码生成并上传逻辑完善,二维码管理后台功能实现以及其他逻辑优化

This commit is contained in:
2025-02-14 16:44:44 +08:00
parent 62c372c456
commit d02ec0f324
15 changed files with 362 additions and 70 deletions
@@ -4,10 +4,10 @@ import com.central.common.model.FileInfo;
import com.central.common.model.PageResult;
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.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@@ -17,6 +17,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -30,14 +31,17 @@ public class FileController {
@Autowired
private IFileService fileService;
// @Value("tencent.accessTokenUrl")
private String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx30a3c8de94a85584&secret=e64d6e3dcfe88d0daee50e77f5a2ee69";
@Value("${zlt.security.tencent.accessTokenUrl}")
private String accessTokenUrl;
// @Value("tencent.getwxacodeUrl")
private String getwxacodeUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
@Value("${zlt.security.tencent.getwxacodeUrl}")
private String getwxacodeUrl;
private RestTemplate restTemplate = new RestTemplate();
@Value("${zlt.security.tencent.pagePath}")
private Object pagePath;
/**
* 文件上传
* 根据fileType选择上传方式
@@ -74,7 +78,13 @@ public class FileController {
*/
@GetMapping("/files")
public PageResult<FileInfo> findFiles(@RequestParam Map<String, Object> params) {
return fileService.findList(params);
PageResult<FileInfo> pageResult = fileService.findList(params);
if(pageResult.getCount() >0){
for (FileInfo fileInfo: pageResult.getData()){
fileInfo.setUrl(getViewUrlByName(fileInfo.getName()));
}
}
return pageResult;
}
@GetMapping("/files/{id}")
@@ -109,7 +119,7 @@ public class FileController {
FileInfo fileInfo = fileService.upload(codeId+".jpeg",getQRCode(accessToken,codeId));
map.put("codeId", codeId);
map.put("fileId", fileInfo.getId());
map.put("filePath", fileInfo.getPath());
map.put("fileName", fileInfo.getName());
return Result.succeed(map);
}
@@ -149,17 +159,26 @@ public class FileController {
* @return
*/
public InputStream getQRCode(String accessToken, String codeId) {
String url = getwxacodeUrl + accessToken; // 确保这里拼接正确,可能还需要其他参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> params = new LinkedHashMap<>();
params.put("path", "/pages/link/link?uuid=" + codeId);
HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(getwxacodeUrl+accessToken, HttpMethod.POST, requestEntity, String.class);
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("path", pagePath + codeId);
HttpEntity<Map> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(
getwxacodeUrl+accessToken, // 假设path参数是这样传递的
HttpMethod.POST, // 或者POST,取决于API要求
requestEntity,
byte[].class); // 直接请求二进制数据
if (responseEntity.getStatusCode().is2xxSuccessful()) {
return new ByteArrayInputStream(HexToJpeg.hexStringToByteArray(responseEntity.getBody()));
}else {
throw new RuntimeException();
byte[] qrCodeBytes = responseEntity.getBody();
// 这里可以直接将字节数组转换为InputStream并返回,或者上传到OSS
InputStream qrCodeStream = new ByteArrayInputStream(qrCodeBytes);
return qrCodeStream; // 如果确实需要返回InputStream,则这样返回
} else {
throw new RuntimeException("Failed to fetch QR code: " + responseEntity.getStatusCode());
}
}
}
@@ -16,11 +16,16 @@ public class HexToJpeg {
}
}
public static byte[] hexStringToByteArray(String hex) {
// 检查字符串长度是否为偶数
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid hex string length: " + hex.length());
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
// 这里应该是安全的,因为我们已经检查了字符串长度是偶数
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
@@ -178,8 +178,6 @@ public class OrderController {
LoginAppUser user = LoginUserContextHolder.getUser();
//@TODO 设置价格逻辑优化
order.setOrderAmount("1990");
order.setUserId(user.getId());
order.setTenantId(TenantContextHolder.getTenant());
@@ -191,6 +189,7 @@ public class OrderController {
if (qrCode != null){
order.setTourismId(qrCode.getTourismId());
order.setDeviceSn(qrCode.getDeviceSn());
order.setOrderAmount(qrCode.getPrice());
}
boolean result = orderService.createOrder(order);
if (result) {
@@ -119,7 +119,6 @@ public class OrderFileController {
if (!CollectionUtils.isEmpty(orderFiles)) {
for (OrderFile orderFile : orderFiles) {
String viewUrl = fileCenterService.getViewUrl(orderFile.getFileId());
System.out.println("viewUrl:"+ viewUrl);
orderFile.setViewUrl(viewUrl);
}
}else {
@@ -4,6 +4,7 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.feign.FileCenterService;
import com.central.order.model.QrCode;
import com.central.order.model.Tourism;
import com.central.order.service.IQrCodeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -47,20 +48,29 @@ public class QrCodeController {
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return qrCodeService.findList(params);
PageResult<QrCode> pageResult = qrCodeService.findList(params);
if (pageResult.getResp_code() == 0){
for (QrCode qrCode: pageResult.getData()){
qrCode.setViewUrl(fileCenterService.getViewUrlByName(qrCode.getPath()));
}
}
return pageResult;
}
@Operation(summary = "生成景区二维码")
@PostMapping
public Result<QrCode> createQrCode(@RequestBody QrCode qrCode) throws Exception {
String codeId = UUID.randomUUID().toString();
public Result<QrCode> saveOrUpdateQrcode(@RequestBody QrCode qrCode) throws Exception {
String codeId = "";
if (qrCode.getId() == null){
codeId = UUID.randomUUID().toString();
}
Result<Map> result = fileCenterService.uploadQrCodeFile(codeId);
if (result.getResp_code() == 0){
qrCode.setCodeId(codeId);
qrCode.setTourismId(32L);
qrCode.setPath(result.getData().get("filePath").toString());
qrCode.setPath(result.getData().get("fileName").toString());
qrCode.setFileId(result.getData().get("fileId").toString());
boolean res = qrCodeService.save(qrCode);
boolean res = qrCodeService.saveOrUpdate(qrCode);
if (res) {
return Result.succeed(qrCode,"qrcode创建成功");
} else {
@@ -82,4 +92,9 @@ public class QrCodeController {
}
@DeleteMapping()
public Result delete(@RequestBody Tourism tourism) {
boolean result = qrCodeService.removeById(tourism);
return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败");
}
}
@@ -28,9 +28,14 @@ public class QrCode extends SuperEntity {
private Long tourismId;
private String path;
private transient String viewUrl;
private String fileId;
private Integer status;
private String price;
private String deviceSn;
@TableField(fill = FieldFill.INSERT)
@@ -91,18 +91,18 @@ public class OssTemplate implements InitializingBean {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(size);
objectMetadata.setContentType(contentType);
PutObjectRequest putObjectRequest = new PutObjectRequest(fileProperties.getCos().getBucketName(), objectName, is, objectMetadata);
PutObjectRequest putObjectRequest = new PutObjectRequest(fileProperties.getOss().getBucketName(), objectName, is, objectMetadata);
ossClient.putObject(putObjectRequest);
ObjectInfo obj = new ObjectInfo();
obj.setObjectPath(fileProperties.getCos().getBucketName() + PATH_SPLIT + objectName);
obj.setObjectUrl(fileProperties.getCos().getEndpoint() + PATH_SPLIT + obj.getObjectPath());
obj.setObjectPath(fileProperties.getOss().getBucketName() + PATH_SPLIT + objectName);
obj.setObjectUrl(fileProperties.getOss().getEndpoint() + PATH_SPLIT + obj.getObjectPath());
return obj;
}
public void delete(String objectName) {
delete(fileProperties.getCos().getBucketName(), objectName);
delete(fileProperties.getOss().getBucketName(), objectName);
}
public void delete(String bucketName, String objectName) {
@@ -132,7 +132,7 @@ public class OssTemplate implements InitializingBean {
public String getViewUrl(String objectName, int expires) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, expires);
URL url = ossClient.generatePresignedUrl(fileProperties.getCos().getBucketName(), objectName, cal.getTime());
URL url = ossClient.generatePresignedUrl(fileProperties.getOss().getBucketName(), objectName, cal.getTime());
return url.toString();
}
@@ -167,7 +167,7 @@ public class OssTemplate implements InitializingBean {
}
public void out(String objectName, OutputStream os) {
out(fileProperties.getS3().getBucketName(), objectName, os);
out(fileProperties.getOss().getBucketName(), objectName, os);
}
/**
@@ -61,6 +61,9 @@ zlt.security.tencent.encodingAESKey=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pTZiyHTxCiQxh
zlt.security.tencent.templateId=YOUR_TEMPLATE_ID
zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session
zlt.security.tencent.accessTokenUrl=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${zlt.security.tencent.appId}&secret=${zlt.security.tencent.appSecret}
zlt.security.tencent.getwxacodeUrl=https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=
zlt.security.tencent.pagePath=/pages/link/link?uuid=
# 微信支付商户号
zlt.wxpay.merchantId=1703796518
@@ -53,6 +53,8 @@ zlt.security.tencent.encodingAESKey=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pTZiyHTxCiQxh
zlt.security.tencent.templateId=YOUR_TEMPLATE_ID
zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session
zlt.security.tencent.accessTokenUrl=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${zlt.security.tencent.appId}&secret=${zlt.security.tencent.appSecret}
zlt.security.tencent.getwxacodeUrl=https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=
zlt.security.tencent.pagePath=/pages/link/link?uuid=
# 微信支付商户号
zlt.wxpay.merchantId=1703796518
@@ -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;
@@ -47,6 +47,11 @@ const TableList: React.FC = () => {
dataIndex: 'size',
valueType: 'digit',
},
{
title: '文件预览',
dataIndex: 'url',
render: (url) => <Image src={url} width={100} />
},
{
title: '媒体类型',
dataIndex: 'contentType',
@@ -72,7 +72,7 @@ const TableList: React.FC = () => {
),
},
{
title: '文件类型',
title: '媒体类型',
dataIndex: 'fileType',
},
{
@@ -0,0 +1,69 @@
import {
ModalForm,
ProForm,
ProFormText,
} from '@ant-design/pro-components';
import { Form } from 'antd';
export type FormValueType = Partial<ORDERS.Tourism>;
export type UpdateFormProps = {
onVisibleChange: (flag: boolean) => void;
onSubmit: (values: FormValueType) => Promise<void>;
updateModalVisible: boolean;
values?: ORDERS.Tourism;
};
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const [form] = Form.useForm();
return (
<ModalForm
title="修改景区"
form={form}
visible={props.updateModalVisible}
onFinish={props.onSubmit}
onVisibleChange={props.onVisibleChange}
>
<ProForm.Group>
<ProFormText
rules={[
{
required: true,
message: '名称不为空',
},
]}
width="md"
name="tourismName"
label="名称"
placeholder="输入名称"
/>
<ProFormText
rules={[
{
required: true,
message: '地址不为空',
},
]}
width="md"
name="tourismAddress"
label="地址"
placeholder="输入地址"
/>
<ProFormText
rules={[
{
required: true,
message: '手机号不为空',
},
]}
width="md"
name="tourismPhone"
label="手机号"
placeholder="输入手机号"
/>
</ProForm.Group>
</ModalForm>
);
};
export default UpdateForm;
@@ -1,38 +1,84 @@
import { qrcode } from '@/services/orders/api';
import { deleteQrcode, qrcode, saveOrUpdateQrcode } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
ModalForm,
PageContainer,
ProForm,
ProFormSelect,
ProFormText,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, Popconfirm } from 'antd';
import { Typography, Popconfirm, Space, message, Image, Button } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
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 handleAdd = async (fields: ORDERS.Qrcode) => {
const hide = message.loading('正在添加');
try {
const result = await saveOrUpdateQrcode({ ...fields });
hide();
if (result.resp_code === 0) {
message.success('添加成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('添加失败');
return false;
}
};
const handleEdit = async (fields: ORDERS.Qrcode) => {
const hide = message.loading('正在更新');
try {
const result = await saveOrUpdateQrcode({ ...fields });
hide();
if (result.resp_code === 0) {
message.success('修改成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('修改失败');
return false;
}
};
const handleDelete = async (qrcode: ORDERS.Qrcode) => {
const hide = message.loading('正在删除');
try {
const result = await deleteQrcode(qrcode.id);
hide();
if (result.resp_code === 0) {
message.success('删除成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('删除失败');
return false;
}
};
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.Qrcode>();
const columns: ProColumns<ORDERS.Qrcode>[] = [
{
dataIndex: 'index',
@@ -51,12 +97,13 @@ const TableList: React.FC = () => {
dataIndex: 'tourismId',
},
{
title: '文件路径',
dataIndex: 'path',
title: '文件',
dataIndex: 'viewUrl',
render: (viewUrl) => <Image src={viewUrl} width={100} />
},
{
title: '文件ID',
dataIndex: 'fileId',
title: '价格',
dataIndex: 'price',
},
{
title: '设备SN',
@@ -74,19 +121,30 @@ const TableList: React.FC = () => {
{
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>,
render: (_, entity) =>
<Space>
<Link
onClick={() => {
setCurrentRow(entity);
handleUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除景区[${entity.codeId}]?`}
onConfirm={async () => {
const success = await handleDelete(entity);
if (success) {
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
>
<Link>删除</Link>
</Popconfirm>
</Space>
},
];
@@ -101,7 +159,7 @@ const TableList: React.FC = () => {
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
</QueryFilter>
<ProTable<ORDERS.Qrcode>
<ProTable<ORDERS.Qrcode>
rowKey="id"
headerTitle="二维码列表"
request={qrcode}
@@ -113,6 +171,102 @@ const TableList: React.FC = () => {
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={() => [
<>
<Button
type="primary"
onClick={() => {
handleModalVisible(true);
}}
>
<PlusOutlined /> 添加
</Button>
</>,
]}
/>
<ModalForm
title="添加二维码"
// layout="horizontal"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
modalProps={{ destroyOnClose: true }}
onFinish={async (values) => {
const success = await handleAdd(values);
if (success) {
handleModalVisible(false);
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
>
<ProForm.Group>
<ProFormSelect
rules={[
{
required: true,
message: '景区不为空',
},
]}
width="md"
name="tourismId"
label="景区"
placeholder="请选择景区"
options={[
{ label: '北塘古镇', value: 33 },
{ label: '海丝首港', value: 32 },
{ label: '景区C', value: 2 },
// 添加更多选项...
]}
/>
<ProFormText
rules={[
{
required: true,
message: '价格不为空',
},
]}
width="md"
name="price"
label="景点打卡价格"
placeholder="输入价格(单位:分)"
/>
<ProFormSelect
rules={[
{
required: true,
message: '设备不为空',
},
]}
width="md"
name="deviceSn"
label="设备编号"
placeholder="输入设备编号"
options={[
{ label: '7CTDM6F00B744S', value: '7CTDM6F00B744S' },
// 添加更多选项...
]}
/>
</ProForm.Group>
</ModalForm>
<UpdateForm
onSubmit={async (values) => {
if (currentRow) {
const success = await handleEdit({ ...currentRow, ...values });
if (success) {
handleUpdateModalVisible(false);
if (actionRef.current) {
actionRef.current.reload();
}
}
setCurrentRow(undefined);
}
}}
onVisibleChange={handleUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
/>
</PageContainer>
);
@@ -60,4 +60,20 @@ export async function qrcode(params?: { [key: string]: string | number }) {
params: { page: current, limit: pageSize, ...rest },
});
return { data: result.data, total: result.count };
}
export async function deleteQrcode(id: number) {
const url = `/api-order/qrcode/${id}`;
const result = await request<API.Result<void>>(url, {
method: 'DELETE',
});
return result;
}
export async function saveOrUpdateQrcode(data: ORDERS.Qrcode): Promise<API.Result<ORDERS.Qrcode>> {
const result = await request<API.Result<ORDERS.Qrcode>>('/api-order/qrcode', {
method: 'POST',
data,
});
return result;
}
@@ -45,6 +45,7 @@ declare namespace ORDERS {
tourismId: string;
path: string;
fileId: string;
price: string;
deviceSn: string;
createTime?: string;
status: number;