first commit

This commit is contained in:
GYJ
2024-12-02 10:29:28 +08:00
commit 03cd33b658
485 changed files with 63600 additions and 0 deletions

View File

@@ -0,0 +1,403 @@
package com.sqx.modules.file;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.file.utils.FileUploadUtils;
import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.model.object.PutObjectFromFileInput;
import com.volcengine.tos.model.object.PutObjectFromFileOutput;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
/**
* 阿里云文件上传
* @author fang
* @date 2020/7/13
*/
@RestController
@Api(value = "阿里云文件上传", tags = {"阿里云文件上传"})
@RequestMapping(value = "/alioss")
@Slf4j
public class AliFileUploadController {
private final CommonInfoService commonRepository;
private AmazonS3 amazonS3;
@Autowired
public AliFileUploadController(CommonInfoService commonRepository, AmazonS3 amazonS3) {
this.commonRepository = commonRepository;
this.amazonS3 = amazonS3;
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ApiOperation("文件上传")
@ResponseBody
public Result upload(@RequestParam("file") MultipartFile file){
String value = commonRepository.findOne(234).getValue();
if("1".equals(value)){
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
// 上传文件流。
InputStream inputStream = null;
try {
inputStream =new ByteArrayInputStream(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String completePath=getPath(suffix);
ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
String src = commonRepository.findOne(72).getValue()+"/"+completePath;
return Result.success().put("data",src);
}else if("2".equals(value)){
String accessKey=commonRepository.findOne(800).getValue();
String secretKey=commonRepository.findOne(801).getValue();
String bucket=commonRepository.findOne(802).getValue();
// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
String path=commonRepository.findOne(804).getValue();
String bucketName=commonRepository.findOne(803).getValue();
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DATE);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(bucket));
// 3 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
File localFile = null;
try {
localFile = File.createTempFile("temp",null);
file.transferTo(localFile);
// 指定要上传到 COS 上的路径
String key = "/duanju/"+year+"/"+month+"/"+day+"/"+newFileName;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
return Result.success().put("data",path + putObjectRequest.getKey());
} catch (IOException e) {
return Result.error(-100,"文件上传失败!");
}finally {
// 关闭客户端(关闭后台线程)
cosclient.shutdown();
}
}else if("3".equals(value)){
String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
// 上传文件流。
InputStream inputStream = null;
try {
inputStream =new ByteArrayInputStream(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String completePath=getPath(suffix);
String bucket=commonRepository.findOne(810).getValue();
com.amazonaws.services.s3.model.PutObjectRequest putObjectRequest = new com.amazonaws.services.s3.model.PutObjectRequest(bucket, completePath, inputStream, new ObjectMetadata());
putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
com.amazonaws.services.s3.model.PutObjectResult putObjectResult = amazonS3.putObject(putObjectRequest);
IOUtils.closeQuietly(inputStream);
return Result.success().put("data",commonRepository.findOne(811).getValue()+"/"+completePath);
}else if("4".equals(value)){
String endpoint = "tos-cn-beijing.volces.com";
String region = "cn-beijing";
String accessKey = commonRepository.findOne(888).getValue();
String secretKey = commonRepository.findOne(889).getValue();
String bucketName = commonRepository.findOne(890).getValue();
// 对象名,模拟 example_dir 下的 example_object.txt 文件
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DATE);
String objectKey = "duanju/"+year+"/"+month+"/"+day+"/"+newFileName;
TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);
FileInputStream fileInputStream = null;
try {
File tempFile = File.createTempFile("temp", null);
file.transferTo(tempFile);
fileInputStream =new FileInputStream(tempFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
PutObjectFromFileInput putObjectInput = new PutObjectFromFileInput()
.setBucket(bucketName).setKey(objectKey).setFileInputStream(fileInputStream);
tos.putObjectFromFile(putObjectInput);
return Result.success().put("data",commonRepository.findOne(891).getValue()+"/"+objectKey);
} catch (Exception e) {
log.error("抖音云上传报错:"+e.getMessage(),e);
}
}else {
try
{
String http = commonRepository.findOne(19).getValue();
String[] split = http.split("://");
// 上传文件路径
String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = http +fileName;
return Result.success().put("data",url);
}
catch (Exception e)
{
log.error("本地上传失败:"+e.getMessage(),e);
return Result.error(-100,"文件上传失败!");
}
}
return Result.error(-100,"文件上传失败!");
}
@RequestMapping(value = "/uploadUniApp", method = RequestMethod.POST)
@ApiOperation("文件上传")
@ResponseBody
public String uploadUniApp(@RequestParam("file") MultipartFile file){
String value = commonRepository.findOne(234).getValue();
if("1".equals(value)){
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
// 上传文件流。
InputStream inputStream = null;
try {
inputStream =new ByteArrayInputStream(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String completePath=getPath(suffix);
ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
return commonRepository.findOne(72).getValue()+"/"+completePath;
}else if("2".equals(value)){
String accessKey=commonRepository.findOne(800).getValue();
String secretKey=commonRepository.findOne(801).getValue();
String bucket=commonRepository.findOne(802).getValue();
// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
String path=commonRepository.findOne(804).getValue();
String bucketName=commonRepository.findOne(803).getValue();
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DATE);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(bucket));
// 3 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
File localFile = null;
try {
localFile = File.createTempFile("temp",null);
file.transferTo(localFile);
// 指定要上传到 COS 上的路径
String key = "/duanju/"+year+"/"+month+"/"+day+"/"+newFileName;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
return path + putObjectRequest.getKey();
} catch (IOException e) {
return null;
}finally {
// 关闭客户端(关闭后台线程)
cosclient.shutdown();
}
}else if("3".equals(value)){
String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
// 上传文件流。
InputStream inputStream = null;
try {
inputStream =new ByteArrayInputStream(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String completePath=getPath(suffix);
String bucket=commonRepository.findOne(810).getValue();
com.amazonaws.services.s3.model.PutObjectRequest putObjectRequest = new com.amazonaws.services.s3.model.PutObjectRequest(bucket, completePath, inputStream, new ObjectMetadata());
putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
com.amazonaws.services.s3.model.PutObjectResult putObjectResult = amazonS3.putObject(putObjectRequest);
IOUtils.closeQuietly(inputStream);
return commonRepository.findOne(811).getValue()+"/"+completePath;
}else if("4".equals(value)){
String endpoint = "tos-cn-beijing.volces.com";
String region = "cn-beijing";
String accessKey = commonRepository.findOne(888).getValue();
String secretKey = commonRepository.findOne(889).getValue();
String bucketName = commonRepository.findOne(890).getValue();
// 对象名,模拟 example_dir 下的 example_object.txt 文件
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DATE);
String objectKey = "duanju/"+year+"/"+month+"/"+day+"/"+newFileName;
TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);
FileInputStream fileInputStream = null;
try {
File tempFile = File.createTempFile("temp", null);
file.transferTo(tempFile);
fileInputStream =new FileInputStream(tempFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
PutObjectFromFileInput putObjectInput = new PutObjectFromFileInput()
.setBucket(bucketName).setKey(objectKey).setFileInputStream(fileInputStream);
tos.putObjectFromFile(putObjectInput);
return commonRepository.findOne(891).getValue()+"/"+objectKey;
} catch (Exception e) {
log.error("抖音云上传报错:"+e.getMessage(),e);
}
}else{
try
{
String http = commonRepository.findOne(19).getValue();
String[] split = http.split("://");
// 上传文件路径
String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = http +fileName;
return url;
}
catch (Exception e)
{
log.error("本地上传失败:"+e.getMessage(),e);
return null;
}
}
return null;
}
private String getPath(String suffix) {
//生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//文件路径
String path =format(new Date()) + "/" + uuid;
return path + suffix;
}
private String format(Date date) {
if(date != null){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
return df.format(date);
}
return null;
}
public static void main(String[] args) {
String endpoint = "tos-cn-beijing.volces.com";
String region = "cn-beijing";
String accessKey = "AKLTZTNjZTI2ZWY3YjU1NDUxNTkwYmY1ZmJhNWYxYzQzNjg";
String secretKey = "WVRWaE9UWmtPV1JtTTJSaU5EWmhORGcxWmpjeE5UUm1OVGt4TVRKbU5tUQ==";
String bucketName = "tt127764ca8d46e23a01-env-2e02vtd07x";
// 对象名,模拟 example_dir 下的 example_object.txt 文件
String objectKey = "duanju/aa1.png";
// 本地文件路径,请保证文件存在,暂不支持文件夹功能
String filePath = "E:\\muban2.png";
TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);
try {
PutObjectFromFileInput putObjectInput = new PutObjectFromFileInput()
.setBucket(bucketName).setKey(objectKey).setFilePath(filePath);
PutObjectFromFileOutput output = tos.putObjectFromFile(putObjectInput);
System.out.println("putObject succeed, object's etag is " + output.getEtag());
System.out.println("putObject succeed, object's crc64 is " + output.getHashCrc64ecma());
} catch (TosClientException e) {
// 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
System.out.println("putObject failed");
System.out.println("Message: " + e.getMessage());
if (e.getCause() != null) {
e.getCause().printStackTrace();
}
} catch (TosServerException e) {
// 操作失败,捕获服务端异常,可以获取到从服务端返回的详细错误信息
System.out.println("putObject failed");
System.out.println("StatusCode: " + e.getStatusCode());
System.out.println("Code: " + e.getCode());
System.out.println("Message: " + e.getMessage());
System.out.println("RequestID: " + e.getRequestID());
} catch (Throwable t) {
// 作为兜底捕获其他异常,一般不会执行到这里
System.out.println("putObject failed");
System.out.println("unexpected exception, message: " + t.getMessage());
}
}
}

View File

@@ -0,0 +1,91 @@
package com.sqx.modules.file;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.sqx.modules.common.service.CommonInfoService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class S3Service {
@Autowired
private AmazonS3 amazonS3;
@Autowired
private CommonInfoService commonInfoService;
private PutObjectResult upload(String filePath, String uploadKey) throws FileNotFoundException {
return upload(new FileInputStream(filePath), uploadKey);
}
private PutObjectResult upload(InputStream inputStream, String uploadKey) {
PutObjectRequest putObjectRequest = new PutObjectRequest(commonInfoService.findOne(810).getValue(), uploadKey, inputStream, new ObjectMetadata());
putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
PutObjectResult putObjectResult = amazonS3.putObject(putObjectRequest);
IOUtils.closeQuietly(inputStream);
return putObjectResult;
}
public List<PutObjectResult> upload(MultipartFile[] multipartFiles) {
List<PutObjectResult> putObjectResults = new ArrayList<>();
Arrays.stream(multipartFiles)
.filter(multipartFile -> !StringUtils.isEmpty(multipartFile.getOriginalFilename()))
.forEach(multipartFile -> {
try {
putObjectResults.add(upload(multipartFile.getInputStream(), multipartFile.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
});
return putObjectResults;
}
public ResponseEntity<byte[]> download(String key) throws IOException {
GetObjectRequest getObjectRequest = new GetObjectRequest(commonInfoService.findOne(810).getValue(), key);
S3Object s3Object = amazonS3.getObject(getObjectRequest);
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);
String fileName = URLEncoder.encode(key, "UTF-8").replaceAll("\\+", "%20");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentLength(bytes.length);
httpHeaders.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
}
public List<S3ObjectSummary> list() {
ObjectListing objectListing = amazonS3.listObjects(new ListObjectsRequest().withBucketName(commonInfoService.findOne(810).getValue()));
List<S3ObjectSummary> s3ObjectSummaries = objectListing.getObjectSummaries();
return s3ObjectSummaries;
}
}

View File

@@ -0,0 +1,34 @@
package com.sqx.modules.file.config;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.sqx.modules.common.service.CommonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
@Component
public class AWSConfiguration {
@Autowired
private CommonInfoService commonInfoService;
@Bean
public BasicAWSCredentials basicAWSCredentials() {
return new BasicAWSCredentials(commonInfoService.findOne(807).getValue(), commonInfoService.findOne(808).getValue());
}
@Bean
public AmazonS3 amazonS3Client(AWSCredentials awsCredentials) {
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
builder.withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
builder.setRegion(commonInfoService.findOne(809).getValue());
AmazonS3 amazonS3 = builder.build();
return amazonS3;
}
}

View File

@@ -0,0 +1,34 @@
package com.sqx.modules.file.utils;
public class DescribeException extends RuntimeException{
private Integer code;
/**
* 继承exception加入错误状态值
* @param exceptionEnum
*/
public DescribeException(ExceptionEnum exceptionEnum) {
super(exceptionEnum.getMsg());
this.code = exceptionEnum.getCode();
}
/**
* 自定义错误信息
* @param message
* @param code
*/
public DescribeException(String message, Integer code) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}

View File

@@ -0,0 +1,49 @@
package com.sqx.modules.file.utils;
public enum ExceptionEnum {
UNKNOW_ERROR(-1, "未知错误"),
LIMIT_USER(-100, "账号已经禁用,请联系管理员!"),
USER_NOT_FIND(-101, "用户未注册"),
USER_IS_BIND_FOR_ANTHER_OPENID(-99, "当前手机号已经被其他微信绑定"),
WRONT_TOKEN(-102, "用户信息失效,请重新登录"),
USER_PWD_EMPTY(-103, "用户名密码不能为空"),
USER_PWD_ERROR(-104, "用户名或密码错误"),
USER_IS_EXITS(-105, "手机号已经注册!"),
ERROR(-106, "服务器内部错误"),
UPDATE_PWD_ERROR(-107, "密码修改失败"),
STATE_PWD_ERROR(-108, "状态修改失败"),
DATA_EMPTY(-109, "添加数据不能为空"),
Return_ATA_EMPTY(-110, "暂无数据"),
ADD_ERROR(-111, "提现失败"),
CODE_ERROR(-112, "验证码不正确"),
BIND_ERROR(-113, "手机号已经被其他账号绑定"),
SEND_ERROR(-114, "验证码发送失败"),
USER_PHONE_ERROR(-115, "用户名不能为空"),
OLD_PWD_ERROR(-116, "原始密码错误"),
IS_REGISTER(-117, "当前手机号已经绑定其他微信账号"),
IS_BIND(-118, "当前淘宝账号已经绑定其他手机号"),
IS_BIND_RELATION(-119, "当前账号已经绑定其他淘宝账号"),
OLD_NOT_SAME_NEW_PWD_ERROR(-120, "新密码不能等于和原始密码一致"),
USER_IS_REGISTER(-121, "用户已经注册请前往登录"),
RELATIONID_IS_REGISTER(-122, "淘宝账号已经授权绑定其他手机号"),
CODE_NOT_FOUND(-123, "邀请码不存在"),
COMMON_IS_EXITS(-124, "已经存在"),
COUPONS_ZERO(-125, "优惠券被领完了"),
COUPONS_GET_OUT(-126, "优惠券超过领取次数"),
COUPONS_TIME_OUT(-127, "优惠券已过期");
private Integer code;
private String msg;
ExceptionEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}

View File

@@ -0,0 +1,234 @@
package com.sqx.modules.file.utils;
import com.sqx.modules.common.service.CommonInfoService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
* 文件上传工具类
*
* @author ruoyi
*/
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 int counter = 0;
private static CommonInfoService commonRepository;
@Autowired
public void setCommonRepository(CommonInfoService commonRepository) {
FileUploadUtils.commonRepository = commonRepository;
}
public static String getDefaultBaseDir()
{
return commonRepository.findOne(19).getValue();
}
/**
* 以默认配置进行文件上传
*
* @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 上传的文件
* @return 返回上传成功的文件名
*/
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
throws DescribeException,IOException
{
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new DescribeException("文件名太长",-100);
}
assertAllowed(file, allowedExtension);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}
/**
* 编码文件名
*/
public static final String extractFilename(MultipartFile file)
{
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
fileName =datePath() + "/" + encodingFilename(fileName) + "." + extension;
return fileName;
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
{
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.getParentFile().exists())
{
desc.getParentFile().mkdirs();
}
if (!desc.exists())
{
desc.createNewFile();
}
return desc;
}
private static final String getPathFileName(String uploadDir, String fileName) throws IOException
{
int dirLastIndex = uploadDir.lastIndexOf("/") + 1;
String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
String pathFileName = "/file/" + currentDir + "/" + fileName;
return pathFileName;
}
/**
* 编码文件名
*/
private static final String encodingFilename(String fileName)
{
fileName = fileName.replace("_", " ");
fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
return fileName;
}
/**
* 文件大小校验
*
* @param file 上传的文件
* @return
*/
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
throws DescribeException
{
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
{
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
{
throw new DescribeException("",-100);
}
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
{
throw new DescribeException("",-100);
}
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
{
throw new DescribeException("",-100);
}
else
{
throw new DescribeException("",-100);
}
}
}
/**
* 判断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(file.getContentType());
}
return extension;
}
}

View File

@@ -0,0 +1,137 @@
package com.sqx.modules.file.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
/**
* 文件处理工具类
*
* @author ruoyi
*/
public class FileUtils
{
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
/**
* 输出指定文件的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
{
if (os != null)
{
try
{
os.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
fis.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}
/**
* 文件名称验证
*
* @param filename 文件名称
* @return true 正常 false 非法
*/
public static boolean isValidFilename(String filename)
{
return filename.matches(FILENAME_PATTERN);
}
/**
* 下载文件名重新编码
*
* @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;
}
}

View File

@@ -0,0 +1,140 @@
package com.sqx.modules.file.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Md5加密方法
*
* @author ruoyi
*/
public class Md5Utils
{
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
private static byte[] md5(String s)
{
MessageDigest algorithm;
try
{
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
byte[] messageDigest = algorithm.digest();
return messageDigest;
}
catch (Exception e)
{
log.error("MD5 Error...", e);
}
return null;
}
private static final String toHex(byte hash[])
{
if (hash == null)
{
return null;
}
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++)
{
if ((hash[i] & 0xff) < 0x10)
{
buf.append("0");
}
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
public static String hash(String s)
{
try
{
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return s;
}
}
public static String md5s(String plainText) {
StringBuffer buf = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return buf.toString();
}
public static String encodeUrlString(String str, String charset) {
String strret = null;
if (str == null){
return str;
}
try {
strret = java.net.URLEncoder.encode(str, charset);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return strret;
}
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = reader.readLine();
if (strRead != null) {
sbf.append(strRead);
while ((strRead = reader.readLine()) != null) {
sbf.append("\n");
sbf.append(strRead);
}
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,59 @@
package com.sqx.modules.file.utils;
/**
* 媒体类型工具类
*
* @author ruoyi
*/
public class MimeTypeUtils
{
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_BMP = "image/bmp";
public static final String IMAGE_GIF = "image/gif";
public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };
public static final String[] FLASH_EXTENSION = { "swf", "flv" };
public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb" };
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
// 图片
"bmp", "gif", "jpg", "jpeg", "png",
// word excel powerpoint
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
// 压缩文件
"rar", "zip", "gz", "bz2",
// 安卓ios更新包
"apk", "ipa",
//视频格式
"mp4","mp3","3GP","AVI","mov","rmvb",
// 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 "";
}
}
}