Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in / Register
Toggle navigation
D
dsk-operate-sys-cscec
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
fulixin
dsk-operate-sys-cscec
Commits
5360d775
Commit
5360d775
authored
Aug 31, 2023
by
lcl
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
资料文档相关代码迁移
parent
a9189dd4
Changes
9
Show whitespace changes
Inline
Side-by-side
Showing
9 changed files
with
1753 additions
and
88 deletions
+1753
-88
InvalidExtensionException.java
.../dsk/common/exception/file/InvalidExtensionException.java
+82
-0
FileTypeUtils.java
...rc/main/java/com/dsk/common/utils/file/FileTypeUtils.java
+77
-0
FileUploadUtils.java
.../main/java/com/dsk/common/utils/file/FileUploadUtils.java
+236
-0
MimeTypeUtils.java
...rc/main/java/com/dsk/common/utils/file/MimeTypeUtils.java
+18
-0
IdUtils.java
...mmon/src/main/java/com/dsk/common/utils/uuid/IdUtils.java
+49
-0
Seq.java
dsk-common/src/main/java/com/dsk/common/utils/uuid/Seq.java
+87
-0
UUID.java
dsk-common/src/main/java/com/dsk/common/utils/uuid/UUID.java
+485
-0
BusinessFileController.java
...n/java/com/dsk/biz/controller/BusinessFileController.java
+85
-88
OldFileUtils.java
...biz-api/src/main/java/com/dsk/biz/utils/OldFileUtils.java
+634
-0
No files found.
dsk-common/src/main/java/com/dsk/common/exception/file/InvalidExtensionException.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
exception
.
file
;
import
org.apache.tomcat.util.http.fileupload.FileUploadException
;
import
java.util.Arrays
;
/**
* 文件上传 误异常类
*
* @author dsk
*/
public
class
InvalidExtensionException
extends
FileUploadException
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
[]
allowedExtension
;
private
String
extension
;
private
String
filename
;
public
InvalidExtensionException
(
String
[]
allowedExtension
,
String
extension
,
String
filename
)
{
super
(
"文件["
+
filename
+
"]后缀["
+
extension
+
"]不正确,请上传"
+
Arrays
.
toString
(
allowedExtension
)
+
"格式"
);
this
.
allowedExtension
=
allowedExtension
;
this
.
extension
=
extension
;
this
.
filename
=
filename
;
}
public
String
[]
getAllowedExtension
()
{
return
allowedExtension
;
}
public
String
getExtension
()
{
return
extension
;
}
public
String
getFilename
()
{
return
filename
;
}
public
static
class
InvalidImageExtensionException
extends
InvalidExtensionException
{
private
static
final
long
serialVersionUID
=
1L
;
public
InvalidImageExtensionException
(
String
[]
allowedExtension
,
String
extension
,
String
filename
)
{
super
(
allowedExtension
,
extension
,
filename
);
}
}
public
static
class
InvalidFlashExtensionException
extends
InvalidExtensionException
{
private
static
final
long
serialVersionUID
=
1L
;
public
InvalidFlashExtensionException
(
String
[]
allowedExtension
,
String
extension
,
String
filename
)
{
super
(
allowedExtension
,
extension
,
filename
);
}
}
public
static
class
InvalidMediaExtensionException
extends
InvalidExtensionException
{
private
static
final
long
serialVersionUID
=
1L
;
public
InvalidMediaExtensionException
(
String
[]
allowedExtension
,
String
extension
,
String
filename
)
{
super
(
allowedExtension
,
extension
,
filename
);
}
}
public
static
class
InvalidVideoExtensionException
extends
InvalidExtensionException
{
private
static
final
long
serialVersionUID
=
1L
;
public
InvalidVideoExtensionException
(
String
[]
allowedExtension
,
String
extension
,
String
filename
)
{
super
(
allowedExtension
,
extension
,
filename
);
}
}
}
dsk-common/src/main/java/com/dsk/common/utils/file/FileTypeUtils.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
utils
.
file
;
import
org.apache.commons.lang3.StringUtils
;
import
java.io.File
;
/**
* 文件类型工具类
*
* @author dsk
*/
public
class
FileTypeUtils
{
/**
* 获取文件类型
* <p>
* 例如: dsk.txt, 返回: txt
*
* @param file 文件名
* @return 后缀(不含".")
*/
public
static
String
getFileType
(
File
file
)
{
if
(
null
==
file
)
{
return
StringUtils
.
EMPTY
;
}
return
getFileType
(
file
.
getName
());
}
/**
* 获取文件类型
* <p>
* 例如: dsk.txt, 返回: txt
*
* @param fileName 文件名
* @return 后缀(不含".")
*/
public
static
String
getFileType
(
String
fileName
)
{
int
separatorIndex
=
fileName
.
lastIndexOf
(
"."
);
if
(
separatorIndex
<
0
)
{
return
""
;
}
return
fileName
.
substring
(
separatorIndex
+
1
).
toLowerCase
();
}
/**
* 获取文件类型
*
* @param photoByte 文件字节码
* @return 后缀(不含".")
*/
public
static
String
getFileExtendName
(
byte
[]
photoByte
)
{
String
strFileExtendName
=
"JPG"
;
if
((
photoByte
[
0
]
==
71
)
&&
(
photoByte
[
1
]
==
73
)
&&
(
photoByte
[
2
]
==
70
)
&&
(
photoByte
[
3
]
==
56
)
&&
((
photoByte
[
4
]
==
55
)
||
(
photoByte
[
4
]
==
57
))
&&
(
photoByte
[
5
]
==
97
))
{
strFileExtendName
=
"GIF"
;
}
else
if
((
photoByte
[
6
]
==
74
)
&&
(
photoByte
[
7
]
==
70
)
&&
(
photoByte
[
8
]
==
73
)
&&
(
photoByte
[
9
]
==
70
))
{
strFileExtendName
=
"JPG"
;
}
else
if
((
photoByte
[
0
]
==
66
)
&&
(
photoByte
[
1
]
==
77
))
{
strFileExtendName
=
"BMP"
;
}
else
if
((
photoByte
[
1
]
==
80
)
&&
(
photoByte
[
2
]
==
78
)
&&
(
photoByte
[
3
]
==
71
))
{
strFileExtendName
=
"PNG"
;
}
return
strFileExtendName
;
}
}
dsk-common/src/main/java/com/dsk/common/utils/file/FileUploadUtils.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
utils
.
file
;
import
com.dsk.common.exception.file.FileNameLengthLimitExceededException
;
import
com.dsk.common.exception.file.FileSizeLimitExceededException
;
import
com.dsk.common.exception.file.InvalidExtensionException
;
import
com.dsk.common.utils.DateUtils
;
import
com.dsk.common.utils.StringUtils
;
import
com.dsk.common.utils.uuid.Seq
;
import
org.apache.commons.io.FilenameUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.io.File
;
import
java.io.IOException
;
import
java.nio.file.Paths
;
import
java.util.Objects
;
/**
* 文件上传工具类
*
* @author dsk
*/
public
class
FileUploadUtils
{
/**
* 默认大小 50M
*/
public
static
final
long
DEFAULT_MAX_SIZE
=
50
*
1024
*
1024
;
/**
* 默认的文件名最大长度 100
*/
public
static
final
int
DEFAULT_FILE_NAME_LENGTH
=
100
;
/**
* 默认上传的地址
*/
private
static
String
defaultBaseDir
=
"/home/server/dsk-operate-sys/uploadPath/"
;
/**
* 资源映射路径 前缀
*/
public
static
final
String
RESOURCE_PREFIX
=
"/profile"
;
public
static
void
setDefaultBaseDir
(
String
defaultBaseDir
)
{
FileUploadUtils
.
defaultBaseDir
=
defaultBaseDir
;
}
public
static
String
getDefaultBaseDir
()
{
return
defaultBaseDir
;
}
/**
* 以默认配置进行文件上传
*
* @param file 上传的文件
* @return 文件名称
* @throws Exception
*/
public
static
final
String
upload
(
MultipartFile
file
)
throws
IOException
{
try
{
return
upload
(
getDefaultBaseDir
(),
file
,
MimeTypeUtils
.
DEFAULT_ALLOWED_EXTENSION
);
}
catch
(
Exception
e
)
{
throw
new
IOException
(
e
.
getMessage
(),
e
);
}
}
/**
* 根据文件路径上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 文件名称
* @throws IOException
*/
public
static
final
String
upload
(
String
baseDir
,
MultipartFile
file
)
throws
IOException
{
try
{
return
upload
(
baseDir
,
file
,
MimeTypeUtils
.
DEFAULT_ALLOWED_EXTENSION
);
}
catch
(
Exception
e
)
{
throw
new
IOException
(
e
.
getMessage
(),
e
);
}
}
/**
* 文件上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param allowedExtension 上传文件类型
* @return 返回上传成功的文件名
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
*/
public
static
final
String
upload
(
String
baseDir
,
MultipartFile
file
,
String
[]
allowedExtension
)
throws
FileSizeLimitExceededException
,
IOException
,
FileNameLengthLimitExceededException
{
int
fileNamelength
=
Objects
.
requireNonNull
(
file
.
getOriginalFilename
()).
length
();
if
(
fileNamelength
>
FileUploadUtils
.
DEFAULT_FILE_NAME_LENGTH
)
{
throw
new
FileNameLengthLimitExceededException
(
FileUploadUtils
.
DEFAULT_FILE_NAME_LENGTH
);
}
assertAllowed
(
file
,
allowedExtension
);
// String fileName = extractFilename(file);
// String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
String
absPath
=
getAbsoluteFile
(
baseDir
,
file
.
getOriginalFilename
()).
getAbsolutePath
();
file
.
transferTo
(
Paths
.
get
(
absPath
));
// return getPathFileName(baseDir, fileName);
return
baseDir
+
file
.
getOriginalFilename
();
}
/**
* 编码文件名
*/
public
static
final
String
extractFilename
(
MultipartFile
file
)
{
return
StringUtils
.
format
(
"{}/{}_{}.{}"
,
DateUtils
.
datePath
(),
FilenameUtils
.
getBaseName
(
file
.
getOriginalFilename
()),
Seq
.
getId
(
Seq
.
uploadSeqType
),
getExtension
(
file
));
}
public
static
final
File
getAbsoluteFile
(
String
uploadDir
,
String
fileName
)
throws
IOException
{
File
desc
=
new
File
(
uploadDir
+
File
.
separator
+
fileName
);
if
(!
desc
.
exists
())
{
if
(!
desc
.
getParentFile
().
exists
())
{
desc
.
getParentFile
().
mkdirs
();
}
}
return
desc
;
}
public
static
final
String
getPathFileName
(
String
uploadDir
,
String
fileName
)
throws
IOException
{
int
dirLastIndex
=
getDefaultBaseDir
().
length
()
+
1
;
String
currentDir
=
StringUtils
.
substring
(
uploadDir
,
dirLastIndex
);
return
RESOURCE_PREFIX
+
"/"
+
currentDir
+
"/"
+
fileName
;
}
/**
* 文件大小校验
*
* @param file 上传的文件
* @return
* @throws FileSizeLimitExceededException 如果超出最大大小
*/
public
static
final
void
assertAllowed
(
MultipartFile
file
,
String
[]
allowedExtension
)
throws
FileSizeLimitExceededException
,
InvalidExtensionException
{
long
size
=
file
.
getSize
();
if
(
size
>
DEFAULT_MAX_SIZE
)
{
throw
new
FileSizeLimitExceededException
(
DEFAULT_MAX_SIZE
/
1024
/
1024
);
}
String
fileName
=
file
.
getOriginalFilename
();
String
extension
=
getExtension
(
file
);
if
(
allowedExtension
!=
null
&&
!
isAllowedExtension
(
extension
,
allowedExtension
))
{
if
(
allowedExtension
==
MimeTypeUtils
.
IMAGE_EXTENSION
)
{
throw
new
InvalidExtensionException
.
InvalidImageExtensionException
(
allowedExtension
,
extension
,
fileName
);
}
else
if
(
allowedExtension
==
MimeTypeUtils
.
FLASH_EXTENSION
)
{
throw
new
InvalidExtensionException
.
InvalidFlashExtensionException
(
allowedExtension
,
extension
,
fileName
);
}
else
if
(
allowedExtension
==
MimeTypeUtils
.
MEDIA_EXTENSION
)
{
throw
new
InvalidExtensionException
.
InvalidMediaExtensionException
(
allowedExtension
,
extension
,
fileName
);
}
else
if
(
allowedExtension
==
MimeTypeUtils
.
VIDEO_EXTENSION
)
{
throw
new
InvalidExtensionException
.
InvalidVideoExtensionException
(
allowedExtension
,
extension
,
fileName
);
}
else
{
throw
new
InvalidExtensionException
(
allowedExtension
,
extension
,
fileName
);
}
}
}
/**
* 判断MIME类型是否是允许的MIME类型
*
* @param extension
* @param allowedExtension
* @return
*/
public
static
final
boolean
isAllowedExtension
(
String
extension
,
String
[]
allowedExtension
)
{
for
(
String
str
:
allowedExtension
)
{
if
(
str
.
equalsIgnoreCase
(
extension
))
{
return
true
;
}
}
return
false
;
}
/**
* 获取文件名的后缀
*
* @param file 表单文件
* @return 后缀名
*/
public
static
final
String
getExtension
(
MultipartFile
file
)
{
String
extension
=
FilenameUtils
.
getExtension
(
file
.
getOriginalFilename
());
if
(
StringUtils
.
isEmpty
(
extension
))
{
extension
=
MimeTypeUtils
.
getExtension
(
Objects
.
requireNonNull
(
file
.
getContentType
()));
}
return
extension
;
}
}
dsk-common/src/main/java/com/dsk/common/utils/file/MimeTypeUtils.java
View file @
5360d775
...
...
@@ -37,4 +37,22 @@ public class MimeTypeUtils {
// pdf
"pdf"
};
public
static
String
getExtension
(
String
prefix
)
{
switch
(
prefix
)
{
case
IMAGE_PNG:
return
"png"
;
case
IMAGE_JPG:
return
"jpg"
;
case
IMAGE_JPEG:
return
"jpeg"
;
case
IMAGE_BMP:
return
"bmp"
;
case
IMAGE_GIF:
return
"gif"
;
default
:
return
""
;
}
}
}
dsk-common/src/main/java/com/dsk/common/utils/uuid/IdUtils.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
utils
.
uuid
;
/**
* ID生成器工具类
*
* @author dsk
*/
public
class
IdUtils
{
/**
* 获取随机UUID
*
* @return 随机UUID
*/
public
static
String
randomUUID
()
{
return
UUID
.
randomUUID
().
toString
();
}
/**
* 简化的UUID,去掉了横线
*
* @return 简化的UUID,去掉了横线
*/
public
static
String
simpleUUID
()
{
return
UUID
.
randomUUID
().
toString
(
true
);
}
/**
* 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 随机UUID
*/
public
static
String
fastUUID
()
{
return
UUID
.
fastUUID
().
toString
();
}
/**
* 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 简化的UUID,去掉了横线
*/
public
static
String
fastSimpleUUID
()
{
return
UUID
.
fastUUID
().
toString
(
true
);
}
}
dsk-common/src/main/java/com/dsk/common/utils/uuid/Seq.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
utils
.
uuid
;
import
com.dsk.common.utils.DateUtils
;
import
com.dsk.common.utils.StringUtils
;
import
java.util.concurrent.atomic.AtomicInteger
;
/**
* @author dsk 序列生成类
*/
public
class
Seq
{
// 通用序列类型
public
static
final
String
commSeqType
=
"COMMON"
;
// 上传序列类型
public
static
final
String
uploadSeqType
=
"UPLOAD"
;
// 通用接口序列数
private
static
AtomicInteger
commSeq
=
new
AtomicInteger
(
1
);
// 上传接口序列数
private
static
AtomicInteger
uploadSeq
=
new
AtomicInteger
(
1
);
// 机器标识
private
static
final
String
machineCode
=
"A"
;
/**
* 获取通用序列号
*
* @return 序列值
*/
public
static
String
getId
()
{
return
getId
(
commSeqType
);
}
/**
* 默认16位序列号 yyMMddHHmmss + 一位机器标识 + 3长度循环递增字符串
*
* @return 序列值
*/
public
static
String
getId
(
String
type
)
{
AtomicInteger
atomicInt
=
commSeq
;
if
(
uploadSeqType
.
equals
(
type
))
{
atomicInt
=
uploadSeq
;
}
return
getId
(
atomicInt
,
3
);
}
/**
* 通用接口序列号 yyMMddHHmmss + 一位机器标识 + length长度循环递增字符串
*
* @param atomicInt 序列数
* @param length 数值长度
* @return 序列值
*/
public
static
String
getId
(
AtomicInteger
atomicInt
,
int
length
)
{
String
result
=
DateUtils
.
dateTimeNow
();
result
+=
machineCode
;
result
+=
getSeq
(
atomicInt
,
length
);
return
result
;
}
/**
* 序列循环递增字符串[1, 10 的 (length)幂次方), 用0左补齐length位数
*
* @return 序列值
*/
private
synchronized
static
String
getSeq
(
AtomicInteger
atomicInt
,
int
length
)
{
// 先取值再+1
int
value
=
atomicInt
.
getAndIncrement
();
// 如果更新后值>=10 的 (length)幂次方则重置为1
int
maxSeq
=
(
int
)
Math
.
pow
(
10
,
length
);
if
(
atomicInt
.
get
()
>=
maxSeq
)
{
atomicInt
.
set
(
1
);
}
// 转字符串,用0左补齐
return
StringUtils
.
padl
(
value
,
length
);
}
}
dsk-common/src/main/java/com/dsk/common/utils/uuid/UUID.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
common
.
utils
.
uuid
;
import
com.dsk.common.exception.UtilException
;
import
java.security.MessageDigest
;
import
java.security.NoSuchAlgorithmException
;
import
java.security.SecureRandom
;
import
java.util.Random
;
import
java.util.concurrent.ThreadLocalRandom
;
/**
* 提供通用唯一识别码(universally unique identifier)(UUID)实现
*
* @author dsk
*/
public
final
class
UUID
implements
java
.
io
.
Serializable
,
Comparable
<
UUID
>
{
private
static
final
long
serialVersionUID
=
-
1185015143654744140L
;
/**
* SecureRandom 的单例
*
*/
private
static
class
Holder
{
static
final
SecureRandom
numberGenerator
=
getSecureRandom
();
}
/** 此UUID的最高64有效位 */
private
final
long
mostSigBits
;
/** 此UUID的最低64有效位 */
private
final
long
leastSigBits
;
/**
* 私有构造
*
* @param data 数据
*/
private
UUID
(
byte
[]
data
)
{
long
msb
=
0
;
long
lsb
=
0
;
assert
data
.
length
==
16
:
"data must be 16 bytes in length"
;
for
(
int
i
=
0
;
i
<
8
;
i
++)
{
msb
=
(
msb
<<
8
)
|
(
data
[
i
]
&
0xff
);
}
for
(
int
i
=
8
;
i
<
16
;
i
++)
{
lsb
=
(
lsb
<<
8
)
|
(
data
[
i
]
&
0xff
);
}
this
.
mostSigBits
=
msb
;
this
.
leastSigBits
=
lsb
;
}
/**
* 使用指定的数据构造新的 UUID。
*
* @param mostSigBits 用于 {@code UUID} 的最高有效 64 位
* @param leastSigBits 用于 {@code UUID} 的最低有效 64 位
*/
public
UUID
(
long
mostSigBits
,
long
leastSigBits
)
{
this
.
mostSigBits
=
mostSigBits
;
this
.
leastSigBits
=
leastSigBits
;
}
/**
* 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。
*
* @return 随机生成的 {@code UUID}
*/
public
static
UUID
fastUUID
()
{
return
randomUUID
(
false
);
}
/**
* 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
*
* @return 随机生成的 {@code UUID}
*/
public
static
UUID
randomUUID
()
{
return
randomUUID
(
true
);
}
/**
* 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
*
* @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能
* @return 随机生成的 {@code UUID}
*/
public
static
UUID
randomUUID
(
boolean
isSecure
)
{
final
Random
ng
=
isSecure
?
Holder
.
numberGenerator
:
getRandom
();
byte
[]
randomBytes
=
new
byte
[
16
];
ng
.
nextBytes
(
randomBytes
);
randomBytes
[
6
]
&=
0x0f
;
/* clear version */
randomBytes
[
6
]
|=
0x40
;
/* set to version 4 */
randomBytes
[
8
]
&=
0x3f
;
/* clear variant */
randomBytes
[
8
]
|=
0x80
;
/* set to IETF variant */
return
new
UUID
(
randomBytes
);
}
/**
* 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。
*
* @param name 用于构造 UUID 的字节数组。
*
* @return 根据指定数组生成的 {@code UUID}
*/
public
static
UUID
nameUUIDFromBytes
(
byte
[]
name
)
{
MessageDigest
md
;
try
{
md
=
MessageDigest
.
getInstance
(
"MD5"
);
}
catch
(
NoSuchAlgorithmException
nsae
)
{
throw
new
InternalError
(
"MD5 not supported"
);
}
byte
[]
md5Bytes
=
md
.
digest
(
name
);
md5Bytes
[
6
]
&=
0x0f
;
/* clear version */
md5Bytes
[
6
]
|=
0x30
;
/* set to version 3 */
md5Bytes
[
8
]
&=
0x3f
;
/* clear variant */
md5Bytes
[
8
]
|=
0x80
;
/* set to IETF variant */
return
new
UUID
(
md5Bytes
);
}
/**
* 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。
*
* @param name 指定 {@code UUID} 字符串
* @return 具有指定值的 {@code UUID}
* @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常
*
*/
public
static
UUID
fromString
(
String
name
)
{
String
[]
components
=
name
.
split
(
"-"
);
if
(
components
.
length
!=
5
)
{
throw
new
IllegalArgumentException
(
"Invalid UUID string: "
+
name
);
}
for
(
int
i
=
0
;
i
<
5
;
i
++)
{
components
[
i
]
=
"0x"
+
components
[
i
];
}
long
mostSigBits
=
Long
.
decode
(
components
[
0
]).
longValue
();
mostSigBits
<<=
16
;
mostSigBits
|=
Long
.
decode
(
components
[
1
]).
longValue
();
mostSigBits
<<=
16
;
mostSigBits
|=
Long
.
decode
(
components
[
2
]).
longValue
();
long
leastSigBits
=
Long
.
decode
(
components
[
3
]).
longValue
();
leastSigBits
<<=
48
;
leastSigBits
|=
Long
.
decode
(
components
[
4
]).
longValue
();
return
new
UUID
(
mostSigBits
,
leastSigBits
);
}
/**
* 返回此 UUID 的 128 位值中的最低有效 64 位。
*
* @return 此 UUID 的 128 位值中的最低有效 64 位。
*/
public
long
getLeastSignificantBits
()
{
return
leastSigBits
;
}
/**
* 返回此 UUID 的 128 位值中的最高有效 64 位。
*
* @return 此 UUID 的 128 位值中最高有效 64 位。
*/
public
long
getMostSignificantBits
()
{
return
mostSigBits
;
}
/**
* 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。
* <p>
* 版本号具有以下含意:
* <ul>
* <li>1 基于时间的 UUID
* <li>2 DCE 安全 UUID
* <li>3 基于名称的 UUID
* <li>4 随机生成的 UUID
* </ul>
*
* @return 此 {@code UUID} 的版本号
*/
public
int
version
()
{
// Version is bits masked by 0x000000000000F000 in MS long
return
(
int
)
((
mostSigBits
>>
12
)
&
0x0f
);
}
/**
* 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。
* <p>
* 变体号具有以下含意:
* <ul>
* <li>0 为 NCS 向后兼容保留
* <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF RFC 4122</a>(Leach-Salz), 用于此类
* <li>6 保留,微软向后兼容
* <li>7 保留供以后定义使用
* </ul>
*
* @return 此 {@code UUID} 相关联的变体号
*/
public
int
variant
()
{
// This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class)
// 1 1 0 Reserved, Microsoft backward compatibility
// 1 1 1 Reserved for future definition.
return
(
int
)
((
leastSigBits
>>>
(
64
-
(
leastSigBits
>>>
62
)))
&
(
leastSigBits
>>
63
));
}
/**
* 与此 UUID 相关联的时间戳值。
*
* <p>
* 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br>
* 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。
*
* <p>
* 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
* 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
*
* @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。
*/
public
long
timestamp
()
throws
UnsupportedOperationException
{
checkTimeBase
();
return
(
mostSigBits
&
0x0FFF
L
)
<<
48
//
|
((
mostSigBits
>>
16
)
&
0x0FFFF
L
)
<<
32
//
|
mostSigBits
>>>
32
;
}
/**
* 与此 UUID 相关联的时钟序列值。
*
* <p>
* 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。
* <p>
* {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出
* UnsupportedOperationException。
*
* @return 此 {@code UUID} 的时钟序列
*
* @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
*/
public
int
clockSequence
()
throws
UnsupportedOperationException
{
checkTimeBase
();
return
(
int
)
((
leastSigBits
&
0x3FFF000000000000
L
)
>>>
48
);
}
/**
* 与此 UUID 相关的节点值。
*
* <p>
* 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。
* <p>
* 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
* 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
*
* @return 此 {@code UUID} 的节点值
*
* @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
*/
public
long
node
()
throws
UnsupportedOperationException
{
checkTimeBase
();
return
leastSigBits
&
0x0000FFFFFFFFFFFF
L
;
}
/**
* 返回此{@code UUID} 的字符串表现形式。
*
* <p>
* UUID 的字符串表示形式由此 BNF 描述:
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @return 此{@code UUID} 的字符串表现形式
* @see #toString(boolean)
*/
@Override
public
String
toString
()
{
return
toString
(
false
);
}
/**
* 返回此{@code UUID} 的字符串表现形式。
*
* <p>
* UUID 的字符串表示形式由此 BNF 描述:
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串
* @return 此{@code UUID} 的字符串表现形式
*/
public
String
toString
(
boolean
isSimple
)
{
final
StringBuilder
builder
=
new
StringBuilder
(
isSimple
?
32
:
36
);
// time_low
builder
.
append
(
digits
(
mostSigBits
>>
32
,
8
));
if
(!
isSimple
)
{
builder
.
append
(
'-'
);
}
// time_mid
builder
.
append
(
digits
(
mostSigBits
>>
16
,
4
));
if
(!
isSimple
)
{
builder
.
append
(
'-'
);
}
// time_high_and_version
builder
.
append
(
digits
(
mostSigBits
,
4
));
if
(!
isSimple
)
{
builder
.
append
(
'-'
);
}
// variant_and_sequence
builder
.
append
(
digits
(
leastSigBits
>>
48
,
4
));
if
(!
isSimple
)
{
builder
.
append
(
'-'
);
}
// node
builder
.
append
(
digits
(
leastSigBits
,
12
));
return
builder
.
toString
();
}
/**
* 返回此 UUID 的哈希码。
*
* @return UUID 的哈希码值。
*/
@Override
public
int
hashCode
()
{
long
hilo
=
mostSigBits
^
leastSigBits
;
return
((
int
)
(
hilo
>>
32
))
^
(
int
)
hilo
;
}
/**
* 将此对象与指定对象比较。
* <p>
* 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。
*
* @param obj 要与之比较的对象
*
* @return 如果对象相同,则返回 {@code true};否则返回 {@code false}
*/
@Override
public
boolean
equals
(
Object
obj
)
{
if
((
null
==
obj
)
||
(
obj
.
getClass
()
!=
UUID
.
class
))
{
return
false
;
}
UUID
id
=
(
UUID
)
obj
;
return
(
mostSigBits
==
id
.
mostSigBits
&&
leastSigBits
==
id
.
leastSigBits
);
}
// Comparison Operations
/**
* 将此 UUID 与指定的 UUID 比较。
*
* <p>
* 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。
*
* @param val 与此 UUID 比较的 UUID
*
* @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。
*
*/
@Override
public
int
compareTo
(
UUID
val
)
{
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return
(
this
.
mostSigBits
<
val
.
mostSigBits
?
-
1
:
//
(
this
.
mostSigBits
>
val
.
mostSigBits
?
1
:
//
(
this
.
leastSigBits
<
val
.
leastSigBits
?
-
1
:
//
(
this
.
leastSigBits
>
val
.
leastSigBits
?
1
:
//
0
))));
}
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/**
* 返回指定数字对应的hex值
*
* @param val 值
* @param digits 位
* @return 值
*/
private
static
String
digits
(
long
val
,
int
digits
)
{
long
hi
=
1L
<<
(
digits
*
4
);
return
Long
.
toHexString
(
hi
|
(
val
&
(
hi
-
1
))).
substring
(
1
);
}
/**
* 检查是否为time-based版本UUID
*/
private
void
checkTimeBase
()
{
if
(
version
()
!=
1
)
{
throw
new
UnsupportedOperationException
(
"Not a time-based UUID"
);
}
}
/**
* 获取{@link SecureRandom},类提供加密的强随机数生成器 (RNG)
*
* @return {@link SecureRandom}
*/
public
static
SecureRandom
getSecureRandom
()
{
try
{
return
SecureRandom
.
getInstance
(
"SHA1PRNG"
);
}
catch
(
NoSuchAlgorithmException
e
)
{
throw
new
UtilException
(
e
);
}
}
/**
* 获取随机数生成器对象<br>
* ThreadLocalRandom是JDK 7之后提供并发产生随机数,能够解决多个线程发生的竞争争夺。
*
* @return {@link ThreadLocalRandom}
*/
public
static
ThreadLocalRandom
getRandom
()
{
return
ThreadLocalRandom
.
current
();
}
}
dsk-module/dsk-biz-api/src/main/java/com/dsk/biz/controller/BusinessFileController.java
View file @
5360d775
...
...
@@ -2,13 +2,13 @@ package com.dsk.biz.controller;
import
com.dsk.biz.domain.bo.BusinessIdDto
;
import
com.dsk.biz.domain.vo.BusinessFileVo
;
import
com.dsk.biz.utils.OldFileUtils
;
import
com.dsk.common.core.controller.BaseController
;
import
com.dsk.common.core.domain.AjaxResult
;
import
com.dsk.common.core.page.TableDataInfo
;
import
com.dsk.common.utils.StringUtils
;
import
com.dsk.common.utils.file.FileUtils
;
import
com.dsk.common.utils.file.FileU
ploadU
tils
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.web.bind.annotation.*
;
import
org.springframework.web.multipart.MultipartFile
;
...
...
@@ -30,90 +30,87 @@ import java.util.stream.Collectors;
@RequestMapping
(
"/business/file"
)
public
class
BusinessFileController
extends
BaseController
{
// @Autowired
// private ServerConfig serverConfig;
//
// /**
// * 新建文件夹
// */
//// @PreAuthorize("@ss.hasPermi('system:file:add')")
//// @Log(title = "项目资料文档", businessType = BusinessType.INSERT)
// @PostMapping("/new")
// public AjaxResult newFolder(@RequestBody(required=false) BusinessIdDto filePath) {
// return FileUtils.newFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
// }
//
// /**
// * 删除某个文件或整个文件夹
// */
// @PostMapping("/remove")
// public AjaxResult removeFile(@RequestBody(required=false) BusinessIdDto filePath) {
// return FileUtils.delFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
// }
//
// /**
// * 分页查询项目的所有文件
// * 获取文件夹中所有文件
// */
// @GetMapping(value = "/list")
// public TableDataInfo getAllFiles(BusinessIdDto filePath) {
// startPage();
// List<BusinessFileVo> allFiles;
// if(StringUtils.isNumeric(filePath.getFilePath())) filePath.setFilePath(ShuZhiHuaConfig.getProfile() + filePath.getFilePath());
// allFiles = FileUtils.getAllFiles(filePath.getFilePath());
// //模糊查询文件
// if(StringUtils.isNotEmpty(filePath.getKeyword())){
// List<BusinessFileVo> allFileName = FileUtils.getAllFileNames(filePath.getFilePath());
// allFiles = allFileName.stream().filter(p -> p.getFilePath().contains(filePath.getKeyword())).collect(Collectors.toList());
// }
// //文件按照时间倒序
// allFiles = allFiles.stream().sorted(Comparator.comparing(BusinessFileVo::getCreatTime).reversed()).collect(Collectors.toList());
// return getDataTable(allFiles);
// }
//
// /**
// * 上传文件及文件夹
// * @param file 文件流
// * @param request 请求头参数
// * @return
// */
// @PostMapping("/upload")
// public AjaxResult uploadFolder(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
// try {
// //获取文件名
// String filename = file.getOriginalFilename();
// String businessFileName = request.getHeader("FilePath");
// // 上传文件路径
// String filePath = ShuZhiHuaConfig.getUploadPath() + businessFileName + "/";
//
// //校验是否上传同名文件
// File newFile = new File(filePath);
// if (newFile.exists()) {
// // 获取当前目录下的文件和文件夹
// File[] files = newFile.listFiles();
// for (File allFile : files) {
// if (filename.equals(allFile.getName())) return error("文件已存在");
// }
// }
//
// // 上传并返回文件全路径
// String fileName = FileUploadUtils.upload(filePath, file);
//// String url = serverConfig.getUrl() + fileName;
// AjaxResult ajax = AjaxResult.success();
// ajax.put("url", fileName);
// return ajax;
// } catch (IOException e) {
// return AjaxResult.error(e.getMessage());
// }
// }
//
// /**
// * 下载文件
// * @param filePath 要下载的文件路径
// * @param response 返回的响应
// */
// @PostMapping("/download")
// public void downloadFolder(@RequestBody BusinessIdDto filePath, HttpServletResponse response) {
// FileUtils.downloadByFilePath(filePath.getFilePath(),response);
// }
/**
* 新建文件夹
*/
// @PreAuthorize("@ss.hasPermi('system:file:add')")
// @Log(title = "项目资料文档", businessType = BusinessType.INSERT)
@PostMapping
(
"/new"
)
public
AjaxResult
newFolder
(
@RequestBody
(
required
=
false
)
BusinessIdDto
filePath
)
{
return
OldFileUtils
.
newFolder
(
filePath
.
getFilePath
())
?
AjaxResult
.
success
()
:
AjaxResult
.
error
();
}
/**
* 删除某个文件或整个文件夹
*/
@PostMapping
(
"/remove"
)
public
AjaxResult
removeFile
(
@RequestBody
(
required
=
false
)
BusinessIdDto
filePath
)
{
return
OldFileUtils
.
delFolder
(
filePath
.
getFilePath
())
?
AjaxResult
.
success
()
:
AjaxResult
.
error
();
}
/**
* 分页查询项目的所有文件
* 获取文件夹中所有文件
*/
@GetMapping
(
value
=
"/list"
)
public
TableDataInfo
getAllFiles
(
BusinessIdDto
filePath
)
{
List
<
BusinessFileVo
>
allFiles
;
if
(
StringUtils
.
isNumeric
(
filePath
.
getFilePath
()))
filePath
.
setFilePath
(
FileUploadUtils
.
getDefaultBaseDir
()
+
filePath
.
getFilePath
());
allFiles
=
OldFileUtils
.
getAllFiles
(
filePath
.
getFilePath
());
//模糊查询文件
if
(
StringUtils
.
isNotEmpty
(
filePath
.
getKeyword
())){
List
<
BusinessFileVo
>
allFileName
=
OldFileUtils
.
getAllFileNames
(
filePath
.
getFilePath
());
allFiles
=
allFileName
.
stream
().
filter
(
p
->
p
.
getFilePath
().
contains
(
filePath
.
getKeyword
())).
collect
(
Collectors
.
toList
());
}
//文件按照时间倒序
allFiles
=
allFiles
.
stream
().
sorted
(
Comparator
.
comparing
(
BusinessFileVo:
:
getCreatTime
).
reversed
()).
collect
(
Collectors
.
toList
());
return
TableDataInfo
.
build
(
allFiles
);
}
/**
* 上传文件及文件夹
* @param file 文件流
* @param request 请求头参数
* @return
*/
@PostMapping
(
"/upload"
)
public
AjaxResult
uploadFolder
(
@RequestPart
(
"file"
)
MultipartFile
file
,
HttpServletRequest
request
)
{
try
{
//获取文件名
String
filename
=
file
.
getOriginalFilename
();
String
businessFileName
=
request
.
getHeader
(
"FilePath"
);
// 上传文件路径
String
filePath
=
FileUploadUtils
.
getDefaultBaseDir
()
+
businessFileName
+
"/"
;
//校验是否上传同名文件
File
newFile
=
new
File
(
filePath
);
if
(
newFile
.
exists
())
{
// 获取当前目录下的文件和文件夹
File
[]
files
=
newFile
.
listFiles
();
for
(
File
allFile
:
files
)
{
if
(
filename
.
equals
(
allFile
.
getName
()))
return
AjaxResult
.
error
(
"文件已存在"
);
}
}
// 上传并返回文件全路径
String
fileName
=
FileUploadUtils
.
upload
(
filePath
,
file
);
// String url = serverConfig.getUrl() + fileName;
AjaxResult
ajax
=
AjaxResult
.
success
();
ajax
.
put
(
"url"
,
fileName
);
return
ajax
;
}
catch
(
IOException
e
)
{
return
AjaxResult
.
error
(
e
.
getMessage
());
}
}
/**
* 下载文件
* @param filePath 要下载的文件路径
* @param response 返回的响应
*/
@PostMapping
(
"/download"
)
public
void
downloadFolder
(
@RequestBody
BusinessIdDto
filePath
,
HttpServletResponse
response
)
{
OldFileUtils
.
downloadByFilePath
(
filePath
.
getFilePath
(),
response
);
}
}
dsk-module/dsk-biz-api/src/main/java/com/dsk/biz/utils/OldFileUtils.java
0 → 100644
View file @
5360d775
package
com
.
dsk
.
biz
.
utils
;
import
com.dsk.biz.domain.vo.BusinessFileVo
;
import
com.dsk.common.exception.base.BaseException
;
import
com.dsk.common.utils.DateUtils
;
import
com.dsk.common.utils.ServletUtils
;
import
com.dsk.common.utils.StringUtils
;
import
com.dsk.common.utils.file.FileTypeUtils
;
import
com.dsk.common.utils.file.FileUploadUtils
;
import
com.dsk.common.utils.file.MimeTypeUtils
;
import
com.dsk.common.utils.uuid.IdUtils
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.io.FilenameUtils
;
import
org.apache.commons.io.IOUtils
;
import
org.apache.commons.lang3.ArrayUtils
;
import
org.apache.http.HttpEntity
;
import
org.apache.http.HttpResponse
;
import
org.apache.http.client.methods.HttpPost
;
import
org.apache.http.entity.ContentType
;
import
org.apache.http.entity.mime.MultipartEntityBuilder
;
import
org.apache.http.entity.mime.content.FileBody
;
import
org.apache.http.impl.client.CloseableHttpClient
;
import
org.apache.http.impl.client.HttpClients
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.*
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.text.SimpleDateFormat
;
import
java.util.ArrayList
;
import
java.util.List
;
/**
* 文件处理工具类
*
* @author dsk
*/
@Slf4j
public
class
OldFileUtils
{
public
static
String
FILENAME_PATTERN
=
"[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"
;
/**
* 检查目录是否存在,如果不存在,则创建目录,如果创建失败则返回false
*
* @param path 文件夹路径
* @return boolean
*/
public
static
boolean
newFolder
(
String
path
)
{
File
file
=
new
File
(
path
);
if
(!
file
.
exists
())
{
boolean
isSuccess
=
file
.
mkdir
();
if
(!
isSuccess
)
if
(!
file
.
exists
())
{
file
.
mkdirs
();
}
return
isSuccess
;
}
else
{
return
true
;
}
}
/**
*
*
* @param folderPath 文件夹路径
* @return 文件夹路径
*/
public
static
String
newFolder1
(
String
folderPath
)
{
String
filePath
=
folderPath
;
try
{
File
myFilePath
=
new
File
(
filePath
);
if
(!
myFilePath
.
exists
())
{
myFilePath
.
mkdirs
();
}
}
catch
(
Exception
e
)
{
log
.
error
(
"创建文件夹失败"
);
filePath
=
""
;
e
.
printStackTrace
();
}
return
filePath
;
}
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public
static
void
writeBytes
(
String
filePath
,
OutputStream
os
)
throws
IOException
{
FileInputStream
fis
=
null
;
try
{
File
file
=
new
File
(
filePath
);
if
(!
file
.
exists
())
{
throw
new
FileNotFoundException
(
filePath
);
}
fis
=
new
FileInputStream
(
file
);
byte
[]
b
=
new
byte
[
1024
];
int
length
;
while
((
length
=
fis
.
read
(
b
))
>
0
)
{
os
.
write
(
b
,
0
,
length
);
}
}
catch
(
IOException
e
)
{
throw
e
;
}
finally
{
IOUtils
.
close
(
os
);
IOUtils
.
close
(
fis
);
}
}
/**
* 写数据到文件中
*
* @param data 数据
* @return 目标文件
* @throws IOException IO异常
*/
public
static
String
writeImportBytes
(
byte
[]
data
)
throws
IOException
{
return
writeBytes
(
data
,
FileUploadUtils
.
getDefaultBaseDir
().
concat
(
"/import"
));
}
/**
* 写数据到文件中
*
* @param data 数据
* @param uploadDir 目标文件
* @return 目标文件
* @throws IOException IO异常
*/
public
static
String
writeBytes
(
byte
[]
data
,
String
uploadDir
)
throws
IOException
{
FileOutputStream
fos
=
null
;
String
pathName
=
""
;
try
{
String
extension
=
getFileExtendName
(
data
);
pathName
=
DateUtils
.
datePath
()
+
"/"
+
IdUtils
.
fastUUID
()
+
"."
+
extension
;
File
file
=
FileUploadUtils
.
getAbsoluteFile
(
uploadDir
,
pathName
);
fos
=
new
FileOutputStream
(
file
);
fos
.
write
(
data
);
}
finally
{
IOUtils
.
close
(
fos
);
}
return
FileUploadUtils
.
getPathFileName
(
uploadDir
,
pathName
);
}
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public
static
boolean
deleteFile
(
String
filePath
)
{
boolean
flag
=
false
;
File
file
=
new
File
(
filePath
);
// 路径为文件且不为空则进行删除
if
(
file
.
isFile
()
&&
file
.
exists
())
{
flag
=
file
.
delete
();
}
return
flag
;
}
/**
* 删除整个文件夹或者文某个文件
*
* @param filePath 文件
* @return
*/
public
static
boolean
delFolder
(
String
filePath
)
{
try
{
delAllFile
(
filePath
);
// 删除里面的所有文件
File
file
=
new
File
(
filePath
);
return
file
.
delete
();
// 删除空文件夹
}
catch
(
Exception
e
)
{
throw
new
BaseException
(
"删除文件夹失败"
,
e
.
getMessage
());
}
}
/**
* 文件夹过滤
*
* @param path 文件夹路径
*/
public
static
void
delAllFile
(
String
path
)
{
String
hint
=
"这是一个根目录,请更换目录!"
;
File
file
=
new
File
(
path
);
if
(!
file
.
exists
())
{
throw
new
BaseException
(
"文件不存在"
);
}
// if (!file.isDirectory()) {
// return false;
// }
if
(
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/"
))
{
throw
new
BaseException
(
hint
);
}
if
(
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/root"
))
{
throw
new
BaseException
(
hint
);
}
if
(
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/usr"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/opt"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/bin"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/sbin"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/etc"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/selinux"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/sys"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/var"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/home"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"/net"
))
{
throw
new
BaseException
(
hint
);
}
if
(
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"C://"
)
||
file
.
getAbsolutePath
().
equalsIgnoreCase
(
"C:\\\\"
))
{
throw
new
BaseException
(
hint
);
}
String
[]
tempList
=
file
.
list
();
File
temp
;
if
(
tempList
==
null
)
{
return
;
}
for
(
String
aTempList
:
tempList
)
{
if
(
path
.
endsWith
(
File
.
separator
))
{
temp
=
new
File
(
path
+
aTempList
);
}
else
{
temp
=
new
File
(
path
+
File
.
separator
+
aTempList
);
}
if
(
temp
.
isFile
())
{
temp
.
delete
();
}
if
(
temp
.
isDirectory
())
{
delAllFile
(
path
+
"/"
+
aTempList
);
// 删除里面的所有文件
delFolder
(
path
+
"/"
+
aTempList
);
// 删除空文件夹
}
}
}
/**
* 获取文件夹中所有文件
* @param filePath 全路径
* @return
*/
public
static
List
<
BusinessFileVo
>
getAllFiles
(
String
filePath
)
{
List
<
BusinessFileVo
>
fileList
=
new
ArrayList
<>();
File
file
=
new
File
(
filePath
);
if
(!
file
.
exists
())
{
return
fileList
;
}
if
(!
file
.
isDirectory
())
{
return
fileList
;
}
// 获取当前目录下的文件和文件夹
File
[]
files
=
file
.
listFiles
();
if
(
files
!=
null
)
{
for
(
File
directory
:
files
)
{
// 如果是文件夹则递归调用此方法
if
(
directory
.
isDirectory
())
{
fileList
.
add
(
new
BusinessFileVo
(
directory
.
getPath
(),
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
).
format
(
directory
.
lastModified
())));
getAllFiles
(
directory
.
getPath
());
}
else
{
// 如果是文件则直接输出路径
fileList
.
add
(
new
BusinessFileVo
(
directory
.
getPath
(),
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
).
format
(
directory
.
lastModified
())));
}
}
return
fileList
;
}
return
fileList
;
}
/**
* 获取文件夹中的所有文件,不包括文件夹
*
* @param path 文件夹路径
* @return List<File>
*/
public
static
List
<
BusinessFileVo
>
getAllFileNames
(
String
path
)
{
List
<
BusinessFileVo
>
fileList
=
new
ArrayList
<>();
File
file
=
new
File
(
path
);
if
(!
file
.
exists
())
{
return
fileList
;
}
if
(!
file
.
isDirectory
())
{
return
fileList
;
}
String
[]
tempList
=
file
.
list
();
File
tempFile
;
for
(
String
fileName
:
tempList
)
{
if
(
path
.
endsWith
(
File
.
separator
))
{
tempFile
=
new
File
(
path
+
fileName
);
}
else
{
tempFile
=
new
File
(
path
+
File
.
separator
+
fileName
);
}
if
(
tempFile
.
isFile
())
{
fileList
.
add
(
new
BusinessFileVo
(
tempFile
.
getPath
(),
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
).
format
(
tempFile
.
lastModified
())));
}
if
(
tempFile
.
isDirectory
())
{
List
<
BusinessFileVo
>
allFiles
=
getAllFileNames
(
tempFile
.
getAbsolutePath
());
fileList
.
addAll
(
allFiles
);
}
}
return
fileList
;
}
/**
* 根据文件路径下载文件
* @param filePath 要下载的文件路径
* @param response 返回的响应
*/
public
static
void
downloadByFilePath
(
String
filePath
,
HttpServletResponse
response
)
{
try
{
// path是指想要下载的文件的路径
File
file
=
new
File
(
filePath
);
// log.info(file.getPath());
if
(!
file
.
exists
())
throw
new
BaseException
(
"文件不存在!"
);
// 获取文件名
String
filename
=
file
.
getName
();
// log.info("文件名: "+filename);
// 获取文件后缀名
// String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
// log.info("文件后缀名:" + ext);
// 将文件写入输入流
FileInputStream
fileInputStream
=
new
FileInputStream
(
file
);
InputStream
fis
=
new
BufferedInputStream
(
fileInputStream
);
byte
[]
buffer
=
new
byte
[
fis
.
available
()];
fis
.
read
(
buffer
);
// 清空response
response
.
reset
();
// 设置response的Header
response
.
setCharacterEncoding
(
"UTF-8"
);
//文件类型
response
.
setContentType
(
"application/octet-stream"
);
response
.
setHeader
(
"Content-Disposition"
,
"attachment;filename="
+
URLEncoder
.
encode
(
filename
,
"UTF-8"
));
//文件名称
response
.
addHeader
(
"Download-filename"
,
URLEncoder
.
encode
(
filename
,
"UTF-8"
));
// 告知浏览器文件的大小
response
.
addHeader
(
"Content-Length"
,
""
+
file
.
length
());
OutputStream
outputStream
=
new
BufferedOutputStream
(
response
.
getOutputStream
());
outputStream
.
write
(
buffer
);
fis
.
close
();
outputStream
.
flush
();
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
}
}
/**
* 根据文件url下载文件
* @param filePath 要下载的文件链接
* @param response 响应体
* @return
* @throws IOException
*/
public
static
void
downloadByUrl
(
String
filePath
,
HttpServletResponse
response
){
// String fileUrl = request.getParameter("fileUrl"); // 获取文件链接
try
{
URL
url
=
new
URL
(
filePath
);
HttpURLConnection
connection
=
(
HttpURLConnection
)
url
.
openConnection
();
connection
.
setRequestMethod
(
"GET"
);
// 设置响应头,告诉浏览器下载文件
String
contentType
=
connection
.
getContentType
();
// 获取文件类型
response
.
setContentType
(
contentType
);
String
filename
=
extractFilenameFromUrl
(
filePath
);
// 从链接中提取文件名
response
.
setHeader
(
"Content-Disposition"
,
"attachment; filename="
+
filename
+
""
);
// 将文件流写入响应输出流
InputStream
inputStream
=
connection
.
getInputStream
();
byte
[]
buffer
=
new
byte
[
4096
];
int
bytesRead
=
-
1
;
while
((
bytesRead
=
inputStream
.
read
(
buffer
))
!=
-
1
)
{
response
.
getOutputStream
().
write
(
buffer
,
0
,
bytesRead
);
}
inputStream
.
close
();
connection
.
disconnect
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
// 从文件链接中提取文件名
public
static
String
extractFilenameFromUrl
(
String
url
)
{
int
slashIndex
=
url
.
lastIndexOf
(
'/'
);
int
dotIndex
=
url
.
lastIndexOf
(
'.'
);
if
(
dotIndex
==
-
1
||
dotIndex
<
slashIndex
)
{
return
"download"
;
}
return
url
.
substring
(
slashIndex
+
1
);
}
/**
* 上传文件
* @param url 上传链接
* @param folderPath 文件路径
* @return
* @throws IOException
*/
public
static
boolean
uploadFolder
(
String
url
,
String
folderPath
)
throws
IOException
{
File
folder
=
new
File
(
folderPath
);
if
(!
folder
.
exists
()
||
!
folder
.
isDirectory
())
{
throw
new
IllegalArgumentException
(
"文件夹路径无效: "
+
folderPath
);
}
List
<
File
>
files
=
new
ArrayList
<>();
listFiles
(
folder
,
files
);
try
(
CloseableHttpClient
httpClient
=
HttpClients
.
createDefault
())
{
HttpPost
httpPost
=
new
HttpPost
(
url
);
MultipartEntityBuilder
builder
=
MultipartEntityBuilder
.
create
();
for
(
File
file
:
files
)
{
FileBody
fileBody
=
new
FileBody
(
file
,
ContentType
.
DEFAULT_BINARY
);
builder
.
addPart
(
"file"
,
fileBody
);
}
HttpEntity
multipart
=
builder
.
build
();
httpPost
.
setEntity
(
multipart
);
HttpResponse
response
=
httpClient
.
execute
(
httpPost
);
int
statusCode
=
response
.
getStatusLine
().
getStatusCode
();
if
(
statusCode
!=
200
)
{
throw
new
RuntimeException
(
"上传文件夹失败: "
+
response
.
getStatusLine
().
getReasonPhrase
());
}
}
return
true
;
}
private
static
void
listFiles
(
File
folder
,
List
<
File
>
files
)
{
File
[]
subFiles
=
folder
.
listFiles
();
for
(
File
subFile
:
subFiles
)
{
if
(
subFile
.
isDirectory
())
{
listFiles
(
subFile
,
files
);
}
else
{
files
.
add
(
subFile
);
}
}
}
/**
* 文件名称验证
*
* @param filename 文件名称
* @return true 正常 false 非法
*/
public
static
boolean
isValidFilename
(
String
filename
)
{
return
filename
.
matches
(
FILENAME_PATTERN
);
}
/**
* 检查文件是否可下载
*
* @param resource 需要下载的文件
* @return true 正常 false 非法
*/
public
static
boolean
checkAllowDownload
(
String
resource
)
{
// 禁止目录上跳级别
if
(
StringUtils
.
contains
(
resource
,
".."
))
{
return
false
;
}
// 检查允许下载的文件规则
if
(
ArrayUtils
.
contains
(
MimeTypeUtils
.
DEFAULT_ALLOWED_EXTENSION
,
FileTypeUtils
.
getFileType
(
resource
)))
{
return
true
;
}
// 不在允许下载的文件规则
return
false
;
}
/**
* 下载文件名重新编码
*
* @param request 请求对象
* @param fileName 文件名
* @return 编码后的文件名
*/
public
static
String
setFileDownloadHeader
(
HttpServletRequest
request
,
String
fileName
)
throws
UnsupportedEncodingException
{
final
String
agent
=
request
.
getHeader
(
"USER-AGENT"
);
String
filename
=
fileName
;
if
(
agent
.
contains
(
"MSIE"
))
{
// IE浏览器
filename
=
URLEncoder
.
encode
(
filename
,
"utf-8"
);
filename
=
filename
.
replace
(
"+"
,
" "
);
}
else
if
(
agent
.
contains
(
"Firefox"
))
{
// 火狐浏览器
filename
=
new
String
(
fileName
.
getBytes
(),
"ISO8859-1"
);
}
else
if
(
agent
.
contains
(
"Chrome"
))
{
// google浏览器
filename
=
URLEncoder
.
encode
(
filename
,
"utf-8"
);
}
else
{
// 其它浏览器
filename
=
URLEncoder
.
encode
(
filename
,
"utf-8"
);
}
return
filename
;
}
/**
* 下载文件名重新编码
*
* @param response 响应对象
* @param realFileName 真实文件名
*/
public
static
void
setAttachmentResponseHeader
(
HttpServletResponse
response
,
String
realFileName
)
throws
UnsupportedEncodingException
{
String
percentEncodedFileName
=
percentEncode
(
realFileName
);
StringBuilder
contentDispositionValue
=
new
StringBuilder
();
contentDispositionValue
.
append
(
"attachment; filename="
)
.
append
(
percentEncodedFileName
)
.
append
(
";"
)
.
append
(
"filename*="
)
.
append
(
"utf-8''"
)
.
append
(
percentEncodedFileName
);
response
.
addHeader
(
"Access-Control-Expose-Headers"
,
"Content-Disposition,download-filename"
);
response
.
setHeader
(
"Content-disposition"
,
contentDispositionValue
.
toString
());
response
.
setHeader
(
"download-filename"
,
percentEncodedFileName
);
}
/**
* 百分号编码工具方法
*
* @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串
*/
public
static
String
percentEncode
(
String
s
)
throws
UnsupportedEncodingException
{
String
encode
=
URLEncoder
.
encode
(
s
,
StandardCharsets
.
UTF_8
.
toString
());
return
encode
.
replaceAll
(
"\\+"
,
"%20"
);
}
/**
* 获取图像后缀
*
* @param photoByte 图像数据
* @return 后缀名
*/
public
static
String
getFileExtendName
(
byte
[]
photoByte
)
{
String
strFileExtendName
=
"jpg"
;
if
((
photoByte
[
0
]
==
71
)
&&
(
photoByte
[
1
]
==
73
)
&&
(
photoByte
[
2
]
==
70
)
&&
(
photoByte
[
3
]
==
56
)
&&
((
photoByte
[
4
]
==
55
)
||
(
photoByte
[
4
]
==
57
))
&&
(
photoByte
[
5
]
==
97
))
{
strFileExtendName
=
"gif"
;
}
else
if
((
photoByte
[
6
]
==
74
)
&&
(
photoByte
[
7
]
==
70
)
&&
(
photoByte
[
8
]
==
73
)
&&
(
photoByte
[
9
]
==
70
))
{
strFileExtendName
=
"jpg"
;
}
else
if
((
photoByte
[
0
]
==
66
)
&&
(
photoByte
[
1
]
==
77
))
{
strFileExtendName
=
"bmp"
;
}
else
if
((
photoByte
[
1
]
==
80
)
&&
(
photoByte
[
2
]
==
78
)
&&
(
photoByte
[
3
]
==
71
))
{
strFileExtendName
=
"png"
;
}
return
strFileExtendName
;
}
/**
* 获取文件名称 /profile/upload/2022/04/16/dsk.png -- dsk.png
*
* @param fileName 路径名称
* @return 没有文件路径的名称
*/
public
static
String
getName
(
String
fileName
)
{
if
(
fileName
==
null
)
{
return
null
;
}
int
lastUnixPos
=
fileName
.
lastIndexOf
(
'/'
);
int
lastWindowsPos
=
fileName
.
lastIndexOf
(
'\\'
);
int
index
=
Math
.
max
(
lastUnixPos
,
lastWindowsPos
);
return
fileName
.
substring
(
index
+
1
);
}
/**
* 获取不带后缀文件名称 /profile/upload/2022/04/16/dsk.png -- dsk
*
* @param fileName 路径名称
* @return 没有文件路径和后缀的名称
*/
public
static
String
getNameNotSuffix
(
String
fileName
)
{
if
(
fileName
==
null
)
{
return
null
;
}
String
baseName
=
FilenameUtils
.
getBaseName
(
fileName
);
return
baseName
;
}
/**
* 获取本地服务的域名,端口
* @return
*/
public
static
String
getUrl
()
{
HttpServletRequest
request
=
ServletUtils
.
getRequest
();
StringBuffer
url
=
request
.
getRequestURL
();
String
contextPath
=
request
.
getServletContext
().
getContextPath
();
return
url
.
delete
(
url
.
length
()
-
request
.
getRequestURI
().
length
(),
url
.
length
()).
append
(
contextPath
).
toString
();
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment