cos工具类 + 上传下载接口cos切换

This commit is contained in:
liyawei
2022-06-08 18:59:54 +08:00
parent d5497cf5bc
commit 1ff997103a
10 changed files with 501 additions and 12 deletions
@@ -19,6 +19,8 @@ public interface IOSSFileService extends IService<OSSFile> {
*/
public OSSFile uploadLocal(MultipartFile mf, String bizPath,String state,String cut);
public OSSFile uploadLocalOfCos(MultipartFile mf, String bizPath,String state,String cut);
public OSSFile uploadLocalForSplit(MultipartFile mf, String bizPath,String state,String cut);
@@ -7,6 +7,7 @@ import com.jero.common.exception.JeroBootException;
import com.jero.common.system.vo.LoginUser;
import com.jero.common.util.CommonUtils;
import com.jero.common.util.oConvertUtils;
import com.jero.common.util.oss.CosBootUtil;
import com.jero.common.util.oss.OssBootUtil;
import com.jero.modules.oss.entity.OSSFile;
import com.jero.modules.oss.mapper.OSSFileMapper;
@@ -164,6 +165,103 @@ public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> impl
return oSSFile;
}
/**
* 本地文件上传 cos
*
* @param mf 文件
* @param bizPath 自定义路径
* @return
*/
@Override
public OSSFile uploadLocalOfCos(MultipartFile mf, String bizPath,String state,String cut) {
//处理文件大小,大于100M抛出异常
long fileSize = mf.getSize() / 1024 / 1024;
String originalFilename = mf.getOriginalFilename();
if (fileSize >= 100) {
if(cut.equals(CutEnum.CN.getValue())){
throw new JeroBootException(originalFilename + "文件大小超出100MB, 请压缩或降低文件质量!");
}else{
throw new JeroBootException(originalFilename + "File size out 100MB, Please compress or reduce file quality!");
}
}
OSSFile oSSFile = new OSSFile();
try {
String ctxPath = uploadpath;
String fileName = null;
String fileType = null;
String orgName = mf.getOriginalFilename();// 获取文件名
orgName = CommonUtils.getFileName(orgName);
if (orgName.indexOf(".") != -1) {
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
} else {
fileName = orgName + "_" + System.currentTimeMillis();
}
String filePath = ctxPath + "/" + fileName;
fileType = orgName.substring(orgName.lastIndexOf("."));
String fileTypeStr = ".doc,.DOC,.docx,.DOCX,.xls, .XLS,.xlsx,.XLSX,.pdf,.PDF";
//判断文件类型
if("1".equals(state)){
//固定文件
if(!fileTypeStr.contains(fileType)){
if(cut.equals(CutEnum.CN.getValue())){
throw new JeroBootException("只能够上传pdf,word,excel类型的文件。请重新选择文件!");
}else{
throw new JeroBootException("Only upload pdf,word,excel type of file Please select the file again");
}
}
}else{
if (CommonUtils.limitFileSuffix(orgName, fileSuffixLimits)) {
if(cut.equals(CutEnum.CN.getValue())){
throw new JeroBootException("不能上传"+StringUtils.join(fileSuffixLimits, ",")+"类型的文件。请重新选择文件!");
}else{
throw new JeroBootException("Can't upload"+StringUtils.join(fileSuffixLimits, ",")+"type of file Please select the file again");
}
}
}
if (StringUtils.isNotEmpty(fileType)) {
String[] fileTypeArr = {".doc",".DOC",".txt",".TXT", ".docx",".DOCX",
".xls", ".XLS",".xlsx",".XLSX", ".pdf",".PDF", ".png",".PNG",
".jfif",".JFIF", ".pjpeg",".PJPEG", ".jpeg",".JPEG", ".pjp",".PJP",
".jpg",".JPG", ".swf",".SWF", ".bmp",".BMP",".rar",".RAR",".zip",".ZIP",".ppt",".PPT",".pptx",".PPTX",".csv",".CSV"};
boolean flag = true;
for (String fileTypeTemp : fileTypeArr) {
if (fileTypeTemp.equalsIgnoreCase(fileType)) {
flag = false;
}
}
if (flag) {
if(cut.equals(CutEnum.CN.getValue())){
throw new JeroBootException("只能够上传pdf/word/excel/csv/ppt/txt/zip/rar/静态图片类型的文件。请重新选择文件!");
}else{
throw new JeroBootException("Only upload pdf/word/excel/csv/ppt/txt/zip/rar/静态图片类型的文件。请重新选择文件!");
}
}
}
// 将文件上传至腾讯云 cos
CosBootUtil.upload(mf, filePath);
LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//存入文件表
oSSFile.setFileName(orgName);
oSSFile.setId(UuidUtils.getUUID());
oSSFile.setUrl(filePath);
oSSFile.setCreateBy(loginUser.getUsername());
oSSFile.setCreateTime(new Date());
this.save(oSSFile);
oSSFile.setUrl(null);
return oSSFile;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return oSSFile;
}
/**
* 本地文件上传-文档拆分专用
*
@@ -11,6 +11,7 @@ import com.jero.common.system.api.ISysBaseAPI;
import com.jero.common.util.RestUtil;
import com.jero.common.util.TokenUtils;
import com.jero.common.util.oConvertUtils;
import com.jero.common.util.oss.CosBootUtil;
import com.jero.modules.oss.entity.OSSFile;
import com.jero.modules.oss.service.IOSSFileService;
import com.jero.modules.system.util.PDFUtils;
@@ -158,14 +159,16 @@ public class CommonController {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
if (oConvertUtils.isEmpty(bizPath)) {
if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
//未指定目录,则用阿里云默认目录 upload
bizPath = "upload";
} else {
bizPath = "";
}
bizPath = "";
// if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
// //未指定目录,则用阿里云默认目录 upload
// bizPath = "upload";
// } else {
// bizPath = "";
// }
}
OSSFile oSSFile = ossFileService.uploadLocal(file, bizPath,state,cut);
// OSSFile oSSFile = ossFileService.uploadLocalOfCos(file, bizPath,state,cut); // 切换cos
if (oConvertUtils.isNotEmpty(oSSFile)) {
result.setResult(oSSFile);
result.setSuccess(true);
@@ -331,8 +334,73 @@ public class CommonController {
}
}
}
}
/**
* word,excel预览 cos
*
* @param id 传入文件id
* @param request
* @param response
*/
// @GetMapping(value = "/downLoadFile")
public void downLoadFromCos(String id,HttpServletRequest request, HttpServletResponse response) {
if(StringUtils.isBlank(id)){
throw new JeroBootException("参数信息不全");
}
id = id.split("\\.")[0];
// 查询数据表数据是否存在
LambdaQueryWrapper<OSSFile> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(OSSFile::getId,id);
OSSFile ossFile = ossFileService.getOne(queryWrapper);
if( null == ossFile){
throw new JeroBootException("文件不存在");
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String fileName = "";
//本地下载
String filePath = ossFile.getUrl();
if(!CosBootUtil.doesObjectExist(filePath)){
response.setStatus(404);
throw new RuntimeException("文件不存在..");
}
// 文件名称
fileName = ossFile.getFileName();
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
outputStream = response.getOutputStream();
inputStream = CosBootUtil.download(filePath);
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
log.error("文件下载失败" + e.getMessage());
response.setStatus(404);
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
/**
* 文件下载
*
@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jero.common.constant.enums.CutEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.jero.common.api.vo.Result;
import com.jero.common.constant.CommonConstant;
@@ -387,6 +388,7 @@ public class SysPermissionController {
*
* @return
*/
@RequiresPermissions("sys:role:auth")
@RequestMapping(value = "/queryRolePermission", method = RequestMethod.GET)
public Result<List<String>> queryRolePermission(@RequestParam(name = "roleId", required = true) String roleId) {
Result<List<String>> result = new Result<>();
@@ -405,6 +407,7 @@ public class SysPermissionController {
*
* @return
*/
@RequiresPermissions("sys:role:auth")
@RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
//@RequiresRoles({ "admin" })
public Result<String> saveRolePermission(@RequestBody JSONObject json) {
@@ -368,7 +368,7 @@ public class SysRoleController {
* @param request
* @return
*/
@RequiresPermissions("sys:role:list")
@RequiresPermissions("sys:role:auth")
@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
public Result<Map<String,Object>> queryTreeList(HttpServletRequest request) {
Result<Map<String,Object>> result = new Result<>();
@@ -271,7 +271,7 @@ public class SysUserController {
* @param userId
* @return
*/
@RequiresPermissions("sys:user:edit")
@RequiresPermissions("sys:user:detail")
@ApiOperation(value = "用户管理-查询用户部门")
@RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
public Result<List<DepartIdModel>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
@@ -318,7 +318,7 @@ public class SysUserController {
* @param userid
* @return
*/
@RequiresPermissions("sys:user:edit")
@RequiresPermissions("sys:user:detail")
@ApiOperation(value = "用户管理-查询用户角色")
@RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {