package com.terra.system.service.data; import com.terra.system.entity.all.SettingData; import com.terra.system.entity.sys.AttachEntity; import com.terra.system.entity.sys.UserEntity; import com.terra.system.helper.FileHelper; import com.terra.system.helper.PathHelper; import com.terra.system.service.sys.AttachService; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 数据检索服务 * @author WWW */ @Service public class DataQueryService { @Resource PathHelper pathHelper; @Resource AttachService attachService; /** * 上传文件 */ public Integer uploadFiles(UserEntity ue, String tabName, String eventid, MultipartFile[] files, HttpServletRequest req) throws IOException { List list = new ArrayList(); for (MultipartFile file : files) { if (file.getSize() > SettingData.MAX_FILE_SIZE) { continue; } // 传输文件 String fileName = file.getOriginalFilename(); String filePath = pathHelper.getTempPath() + File.separator + fileName; File newFile = new File(filePath); file.transferTo(newFile); double sizes = FileHelper.sizeToMb(file.getSize()); // 获取MD5 String md5 = FileHelper.getFileMd5(filePath); AttachEntity entity = attachService.selectByGuid(md5); AttachEntity ae = getAttachEntity(ue, tabName, eventid, fileName, md5, sizes); if (entity != null) { ae.setPath(entity.getPath()); String oldPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath(); File f = new File(oldPath); if (!f.exists() || f.isDirectory()) { newFile.renameTo(new File(oldPath)); } else { newFile.delete(); } } else { String targetPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath(); newFile.renameTo(new File(targetPath)); } list.add(ae); } return attachService.inserts(list); } /** * 获取附件实体类 */ protected AttachEntity getAttachEntity(UserEntity ue, String tabName, String eventid, String fileName, String md5, double sizes) { AttachEntity entity = new AttachEntity(); entity.setTab(tabName); entity.setTabGuid(eventid); entity.setName(fileName); entity.setGuid(md5); String subPath = PathHelper.getUploadPath() + File.separator + md5 + FileHelper.getExtension(fileName); entity.setPath(subPath); entity.setSizes(sizes); if (ue != null) { entity.setCreateUser(ue.getId()); } return entity; } }