Skip to content
AttachmentController.java 11.6 KiB
Newer Older
杨郁彬's avatar
杨郁彬 committed
package com.cesgroup.bdc.attachment.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

杨郁彬's avatar
杨郁彬 committed
import com.cesgroup.bdc.cis.service.CisService;
杨郁彬's avatar
杨郁彬 committed
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cesgroup.bdc.attachment.dto.FileUploaderResponseDto;
import com.cesgroup.bdc.attachment.entity.Attachment;
import com.cesgroup.bdc.attachment.entity.DiskFile;
import com.cesgroup.bdc.attachment.service.IAttachmentService;
import com.cesgroup.bdc.attachment.service.IDiskFileService;
import com.cesgroup.bdc.logs.entity.LogType;
import com.cesgroup.bdc.logs.service.ILogsService;
import com.cesgroup.bdc.util.DownloadUtil;
import com.cesgroup.kingkong.core.security.model.IOrganization;
import com.cesgroup.kingkong.core.security.model.IUser;
import com.cesgroup.kingkong.web.BaseServiceController;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;

/**
 * <p>
 * 附件 前端控制器
 * </p>
 *
 * @author shen.shaohua
 * @since 2019-07-02
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController extends BaseServiceController<Attachment, IAttachmentService> {
  @Autowired
  private IDiskFileService diskFileService;

  @Autowired
  private ILogsService logsService;

杨郁彬's avatar
杨郁彬 committed
  @Autowired
  private CisService cisService;

杨郁彬's avatar
杨郁彬 committed
  /**
   * 默认文件存储路径
   */
  @Value("${file.upload.path}")
  private String fileBasePath;

  /**
   * 文件上传
   * <p>
   * 1.上传文件对应的名称默认为:uploadFile
   * 2.返回默认的名称为:files
   * </p>
   *
   * @return 上传的文件
   * @author: shen.shaohua
   * @since: 2019/7/2 13:37
   */
  @RequestMapping(value = "/upload/{module}/{relevanceId}", method = RequestMethod.POST)
  @ResponseBody
  public Map<String, List<FileUploaderResponseDto>> saveMultiUpload(@RequestParam("uploadFile") MultipartFile[] files,
                                                                    @PathVariable String module, @PathVariable String relevanceId,
                                                                    HttpSession session) {
    Map<String, List<FileUploaderResponseDto>> result = new HashMap<>();
    //HttpServletRequest request = SpringMvcWebUtils.getRequest();
    try {
      String fileRelativePath = DateFormatUtils.format(new Date(), "yyyyMM") + File.separatorChar;
      IUser uu = getUser();
      IOrganization org = getOrg(session);
      List<FileUploaderResponseDto> responseDtos = this.getBaseService().saveMultiFile2(files, module, relevanceId, fileRelativePath, uu, org);
      //与组件库对应的固定写法
      result.put("files", responseDtos);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
    return result;
  }
  @RequestMapping("/updateSecurityLevelFile")
  @ResponseBody
  public Map<String, String> updateSecurityLevelFile (String ids, String securityLevelFile,HttpSession session) {
    String[] idArr = ids.split(",");
    List<String> idList = CollUtil.newArrayList(idArr);
    QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
    queryWrapper.in("id",idList);
    List<Attachment> attachments= this.getBaseService().list(queryWrapper);
    attachments.forEach(a->{
      a.setSecurityLevelFile(securityLevelFile);
    });
    boolean result =  this.getBaseService().saveOrUpdateBatch(attachments);
    Map<String, String> mm = new HashMap<>();
    if(result){
      mm.put("code", "0");
    }else{
      mm.put("code", "-1");
    }
    return mm;
  }

  /**
   * 下载
   *
   * @param id       文件id
   * @param response
   * @author: shen.shaohua
   * @since: 2019/7/9 16:46
   */
  @RequestMapping(value = "/download/{id}")
  public void download(@PathVariable(value = "id") String id, HttpServletResponse response, HttpServletRequest request) {
    FileInputStream fis = null;
    ServletOutputStream sos = null;
    try {
      Attachment attachment = getBaseService().getById(id);
      DiskFile diskFile = diskFileService.getById(attachment.getDiskFileId());
      File file = getBaseService().getOfdFileByAttachment(attachment);
      if (file.exists()) {
        response.setStatus(200);
        response.setContentType("application/x-msdownload");
        String fileName = diskFile.getOriginalName();
        fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".ofd";
        response.setHeader("Content-Disposition", DownloadUtil.getContentDisposition(request, fileName));
        sos = response.getOutputStream();
        byte[] buffer = new byte[1024 * 1024];
        response.setContentLength((int) file.length());
        fis = new FileInputStream(file);
        int readBytes = -1;
        while ((readBytes = fis.read(buffer)) != -1) {
          sos.write(buffer, 0, readBytes);
        }
        logsService.operateLog(request, this.getUser().getId(), this.getUser().getUserName(), LogType.DOWNLOAD, "成功", "附件", "", "收件箱", diskFile.getOriginalName() + "." + diskFile.getExt());

        sos.flush();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IoUtil.close(fis);
      IoUtil.close(sos);
    }
  }

  /**
   * 下载原附件
   *
   * @param id       文件id
   * @param response
   * @author: shen.shaohua
   * @since: 2019/9/22 20:57
   */
  @RequestMapping(value = "/downloadOriginal/{id}")
  public void downloadOriginal(@PathVariable(value = "id") String id, HttpServletResponse response, HttpServletRequest request) {
    FileInputStream fis = null;
    ServletOutputStream sos = null;
    try {
      Attachment attachment = getBaseService().getById(id);
      DiskFile diskFile = diskFileService.getById(attachment.getDiskFileId());
      File file = getBaseService().getFileByAttachment(attachment);
      if (file.exists()) {
        response.setStatus(200);
        response.setContentType("application/x-msdownload");
        String fileName = diskFile.getOriginalName();
        ;
        response.setHeader("Content-Disposition", DownloadUtil.getContentDisposition(request, fileName));
        sos = response.getOutputStream();
        byte[] buffer = new byte[1024 * 1024];
        response.setContentLength((int) file.length());
        fis = new FileInputStream(file);
        int readBytes = -1;
        while ((readBytes = fis.read(buffer)) != -1) {
          sos.write(buffer, 0, readBytes);
        }
        logsService.operateLog(request, this.getUser().getId(), this.getUser().getUserName(), LogType.DOWNLOAD, "成功", "附件", "", "收件箱", diskFile.getOriginalName() + "." + diskFile.getExt());

        sos.flush();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IoUtil.close(fis);
      IoUtil.close(sos);
    }
  }

  /**
   * 下载
   *
   * @param id       文件id
   * @param response
   * @author: shen.shaohua
   * @since: 2019/9/16 19:11
   */
  @RequestMapping(value = "/viewOfd/{id}")
  public void viewOfd(@PathVariable(value = "id") String id, HttpServletResponse response, HttpServletRequest request) {
    FileInputStream fis = null;
    ServletOutputStream sos = null;
    try {
      Attachment attachment = getBaseService().getById(id);
      DiskFile diskFile = diskFileService.getById(attachment.getDiskFileId());
      File file = getBaseService().getOfdFileByAttachment(attachment);
      if (file.exists()) {

        response.setStatus(200);
        response.setContentType("application/x-msdownload");
        String fileName = diskFile.getOriginalName();
        fileName = fileName.substring(0, fileName.lastIndexOf('.')) + ".ofd";
        response.setHeader("Content-Disposition", DownloadUtil.getContentDisposition(request, fileName));
        sos = response.getOutputStream();
        byte[] buffer = new byte[1024 * 1024];
        response.setContentLength((int) file.length());
        fis = new FileInputStream(file);
        int readBytes = -1;
        while ((readBytes = fis.read(buffer)) != -1) {
          sos.write(buffer, 0, readBytes);
        }
        sos.flush();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IoUtil.close(fis);
      IoUtil.close(sos);
    }
  }

  /**
   * 删除附件
   *
   * @param id 附件id
   * @return
   * @author: shen.shaohua
   * @since: 2019/7/2 13:37
   */
  @RequestMapping(value = "/del/{id}")
  @ResponseBody
  public Boolean del(@PathVariable String id) {
    Boolean b = false;
    getBaseService().deleteFile(id);
    b = true;
    return b;
  }

  /**
   * 获取附件列表
   *
   * @param module
   * @param relevanceId
   * @return
   */
  @RequestMapping(value = "/find/{module}/{relevanceId}")
  @ResponseBody
  public List<FileUploaderResponseDto> find(@PathVariable String module, @PathVariable String relevanceId) {
    List<Attachment> attachmentList = getBaseService().selectByModuleAndRelevanceId(module, relevanceId);
    List<FileUploaderResponseDto> list = new ArrayList<>(attachmentList.size());
    for (Attachment attachment : attachmentList) {
      DiskFile diskFile = diskFileService.getById(attachment.getDiskFileId());
      FileUploaderResponseDto dto = new FileUploaderResponseDto(attachment, diskFile);
      list.add(dto);
    }
    return list;
  }

  @RequestMapping(value = "/uploadOnlyOneDZYZ/{attachmentId}", method = RequestMethod.POST)
  @ResponseBody
  public Map<String, Object> uploadOnlyOneDZYZ(@PathVariable String attachmentId,
                                               HttpServletRequest request) {

    MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = mhs.getFileMap();
    System.out.println("通过Map.keySet遍历key和value:");
    MultipartFile mFile = null;
    for (String key : fileMap.keySet()) {
      MultipartFile file = fileMap.get(key);
      mFile = file;
      break;
    }
    Map<String, Object> result = new HashMap<>();
    try {
        
      Attachment attachment = getBaseService().getById(attachmentId);
      File oldFile = getBaseService().getFile(attachment);//原文件

      String oldFileName = oldFile.getName();
      String newFileName = oldFileName.substring(0, oldFileName.lastIndexOf(".")) + ".ofd";
      // 覆盖原有文件
      File newFile = new File(oldFile.getParent(), newFileName);//新文件
      mFile.transferTo(newFile);


杨郁彬's avatar
杨郁彬 committed
      //文件加密
      cisService.encryptedFile(newFile);
杨郁彬's avatar
杨郁彬 committed

      DiskFile diskFile = diskFileService.getById(attachment.getDiskFileId());
      // 更新文件大小
      diskFile.setFileSize(FileUtil.size(newFile));
      diskFileService.updateById(diskFile);
      result.put("status", "success");
    } catch (Exception e) {
      e.printStackTrace();
      result.put("status", "error");
      result.put("errMsg", e.toString());
    }
    return result;
  }
}