Skip to content

Commit

Permalink
fix: 限制文件上传大小
Browse files Browse the repository at this point in the history
  • Loading branch information
lay committed Oct 16, 2024
1 parent ce222e2 commit d02e8a7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 22 deletions.
56 changes: 34 additions & 22 deletions src/pages/workDetail/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ function WorkDetail() {
return urlParts[urlParts.length - 1];
};

const beforeUpload = (file: { size: number }) => {
const isLt2M = file.size / 1024 < 1024 * 500;
if (!isLt2M) {
message.error('文件大小超过500MB限制!');
}
return isLt2M; // 如果文件大小超过500MB,则返回false阻止上传
};

/**
* 文件下载
* @param url 文件url
Expand Down Expand Up @@ -254,32 +262,35 @@ function WorkDetail() {
onChange(info: infoType) {
localFileList = fileList[props.inputName]
console.log('onChange', info)
let newFileList = [...info.fileList]
if (info.file.size > 1024*1024*500) {
form.setValueByPath(props.inputName, null)
} else {
let newFileList = [...info.fileList]

if (info.fileList.length !== 0) {
newFileList = [info.file]
}
if (info.fileList.length !== 0) {
newFileList = [info.file]
}

// 限制文件上传数量
// 只显示最新上传的文件
newFileList = newFileList.slice(-2)
// 限制文件上传数量
// 只显示最新上传的文件
newFileList = newFileList.slice(-2)

// 从文件链接列表读链接
newFileList = newFileList.map((file: any) => {
if (file.response) {
// 以文件链接作为url
file.url = file.response.url
}
return file
})
// console.log('new list', newFileList)
// 从文件链接列表读链接
newFileList = newFileList.map((file: any) => {
if (file.response) {
// 以文件链接作为url
file.url = file.response.url
}
return file
})

setFileList((prev: any) => {
console.log('list updated')
return { ...prev, [props.inputName]: newFileList }
})
if (newFileList.length === 0) {
form.setValueByPath(props.inputName, null)
setFileList((prev: any) => {
console.log('list updated')
return { ...prev, [props.inputName]: newFileList }
})
if (newFileList.length === 0) {
form.setValueByPath(props.inputName, null)
}
}
},
customRequest(options: any) {
Expand Down Expand Up @@ -321,6 +332,7 @@ function WorkDetail() {
// console.log('filelist:', fileList)
return (
<Upload
beforeUpload={beforeUpload}
{...localProps}
customRequest={(options) => {
const temp = options.file as File
Expand Down
13 changes: 13 additions & 0 deletions src/store/formTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import { message } from "antd";

const beforeUpload = (file: { size: number; }) => {
console.log('文件大:');
console.log(file.size);
const isLt2M = file.size / 1024;
if (!isLt2M) {
message.error('文件大小超过1kb限制!');
}
return isLt2M; // 如果文件大小超过2MB,则返回false阻止上传
};

export const tempelate = [
{
type: 'object',
Expand Down Expand Up @@ -85,6 +97,7 @@ export const tempelate = [
props:{
inputName: '视频等附件',
accept: ['.zip','.rar'],
beforeUpload
},
order:9
}
Expand Down

0 comments on commit d02e8a7

Please sign in to comment.