上传附件至linux服务器:
controller层:
点击查看代码
@Override
public Result<?> uploadFile(MultipartHttpServletRequest request,
@RequestParam(value = "businessTable") String businessTable,
@RequestParam(value = "businessId") String businessId,
@RequestParam(value = "businessIds[]", required = false) List<String> businessIds) {
List<AttachmentFileDto> filesInfo = null;
if (StringUtils.isBlank(businessTable))
throw new ControllerException(SimpleErrorCode.ParamsError);
if (CollectionUtils.isNotEmpty(businessIds)) {
//一个文件对应多业务主键
filesInfo = FileUtil.writeManyBusinessFileIntoDisk(request, businessTable, businessIds);
} else if (StringUtils.isNotBlank(businessId) || "T_XTGL_FJ".equals(businessTable)) {
//一个文件对应一个业务主键 上传至文件系统
// filesInfo = FileUtil.writeBusinessFileIntoDisk(request, businessTable, businessId);
filesInfo = FileUtil.uploadFileByFastDFS(request, businessTable, businessId,fastFileStorageClient);
} else {
throw new ControllerException(SimpleErrorCode.ParamsError);
}
return Result.buildSuccessResult(filesInfo);
}
工具类:
点击查看代码
// 单个文件最大允许上传大小50MB
private static final long MAX_SINGLE_FILE_SIZE = 52428800;
// 基础设置的附件根目录
private static String attachmentBasePath;
// 附件表Mapper
private static AttachmentFileMapper attachmentFileMapper;
// 当前服务名
private static String applicationName;
@Value("${spring.application.name}")
public void setapplicationName(String name) {
applicationName = name;
}
/**
* 获取全局设置的附件根目录
*
* @return
*/
public static String getAttachmentBasePath() {
attachmentBasePath = attachmentFileMapper.getSysAttachmentFileRootPath();
attachmentBasePath = StringUtils.isNotBlank(attachmentBasePath) ? attachmentBasePath
: File.separator.concat("higherVocationEduFile").concat(File.separator).concat("attachmentFile");
return attachmentBasePath;
}
/**
* 上传业务附件方法(单个文件对应多个业务主键时调用)
*
* @param request @NotNull
* @param businessTable 业务主表
* @param businessIds 业务主键
* @return
*/
public static List<AttachmentFileDto> writeManyBusinessFileIntoDisk(MultipartHttpServletRequest request,
String businessTable, List<String> businessIds) {
SystemUserInfo systemUserInfo = SessionUtil.getSystemUserInfo(request);
if (systemUserInfo == null) {
throw new ServiceException(SimpleErrorCode.UserNotLogin);
}
// isOverrideAdd 是否覆盖追加(override:覆盖,原有文件将清除,add :追加原有文件保留并追加)
if ("override".equals(request.getParameter("isOverrideAdd"))) {
// 删除硬盘中的文件
List<String> fileIds = deleteBusinessFile(businessTable, businessIds);
}
Date currentDate = new Date();
StringBuffer stringBuffer = new StringBuffer();
List<AttachmentFileDto> list = new ArrayList<>();
AttachmentFileDto entity = null;
MultipartFile file = null;
FileOutputStream out = null;
Iterator<String> itFiles = request.getFileNames();
int i = 0;
while (itFiles.hasNext()) {
i++;
file = request.getFile(itFiles.next());
try {
// 获取文件名
String fileName = request.getParameter("fileName");
String fileUid = request.getParameter("fileUid");
String reFileName = fileName;
long size = file.getSize();
if (size == 0) {
throw new IOException("文件《" + fileName + "》为空");
} else if (size > MAX_SINGLE_FILE_SIZE) {
throw new ServiceException(SimpleErrorCode.SaveFailure.getErrorCode(), "文件《" + fileName + "》太大");
}
// 文件类型
String contentType = file.getContentType();
contentType = StringUtils.isBlank(contentType) ? request.getParameter("fileType") : contentType;
for (int j = 0; j < businessIds.size(); j++) {
if (j > 0) {
reFileName = FilenameUtils.getBaseName(fileName).concat("(" + j + ").")
.concat(FilenameUtils.getExtension(fileName));
}
// 设置文件存储相对路径(服务名/日期/文件名-文件id)
String relativePath = applicationName.concat(File.separator).concat(DateUtils.getDate())
.concat(File.separator).concat(fileUid).concat("-").concat(reFileName);
// 设置文件存储路径(全局根路径/相对路径)
String filePath = FilenameUtils
.normalize(getAttachmentBasePath().concat(File.separator).concat(relativePath));
File dest = new File(filePath);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
// 新建文件夹
dest.getParentFile().mkdirs();
}
log.info("文件保存路径{}", dest.getAbsolutePath());
out = new FileOutputStream(dest);
String businessId = businessIds.get(j);
IOUtils.copy(file.getInputStream(), out);
entity = new AttachmentFileDto();
entity.setRelationalId(uuidStringGenerator.nextUUID());
entity.setUid(fileUid);
entity.setName(fileName);
entity.setFilePath(filePath);
entity.setSize((double) size);
entity.setType(contentType);
entity.setBusinessId(businessId);// 业务主键
entity.setBusinessTable(businessTable);
entity.setService(applicationName);// 服务名
entity.setIsCanbeDownload("1");// 是否可下载
entity.setClientIp(IpUtils.getIp());
entity.setCreateTime(currentDate);
entity.setCreator(systemUserInfo.getUserId());
entity.setCreatorName(systemUserInfo.getName());
entity.setEditTime(currentDate);
entity.setEditor(systemUserInfo.getUserId());
entity.setEditorName(systemUserInfo.getName());
entity.setSchoolCode(systemUserInfo.getSchoolCode());
entity.setSchoolName(systemUserInfo.getSchoolName());
list.add(entity);
}
} catch (IOException e) {
log.error("第 " + i + " 个文件上传失败 ==> ", e);
stringBuffer.append("第 " + i + " 个文件上传失败 ==> " + e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
log.info("附件表数据{}", list);
if (stringBuffer.length() > 0) {
throw new ServiceException(001, stringBuffer.toString());
}
// 记录文件信息到数据库
attachmentFileMapper.batchInsert(list);
return list;
}