欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

上传和下载文件【Java】(图片已流的形式返回)

程序员文章站 2022-04-08 21:39:34
...

Controller

package com.sjasoft.cloud.admin.controller.ems;

import com.sjasoft.cloud.admin.service.ems.SafetyMonitoringService;
import com.sjasoft.framework.spring.bean.Result;
import com.sjasoft.mbg.ems.model.EmsAlert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 安全监控接口
 */
@Controller
@RequestMapping("/ems/safetyMonitoring")
@Api(tags = "SafetyMonitoringController", description = "安全监控接口")
public class SafetyMonitoringController {

    @Autowired
    private SafetyMonitoringService safetyMonitoringService;

    @ResponseBody
    @PostMapping(value = "/createPhoto")
    @ApiOperation(value = "添加报警数据图片报警")
    public Result create(@ApiParam(value = "图片报警", required = true) @RequestParam(value = "multipartFile")MultipartFile multipartFile,@RequestParam(value = "multipartFiles")MultipartFile[] multipartFiles,@RequestParam(value = "uid")String uid) {
        EmsAlert emsAlert = safetyMonitoringService.create(multipartFile, multipartFiles, uid);
        if (emsAlert == null) {
            return Result.failure();
        }
        return Result.success();
    }

    @ResponseBody
    @GetMapping(value = "/downloadPhoto/{fileName}")
    @ApiOperation(value = "下载报警数据图片报警")
    public void download(HttpServletResponse response, HttpServletRequest request, @ApiParam(value = "下载图片报警", required = true) @PathVariable String fileName) {
        safetyMonitoringService.download(response, fileName);
    }


}

Service

package com.sjasoft.cloud.admin.service.ems;

import com.sjasoft.framework.common.utils.StringUtil;
import com.sjasoft.mbg.ems.model.*;
import com.sjasoft.mbg.ems.service.EmsAlertService;
import com.sjasoft.mbg.ems.service.EmsDeployService;
import com.sjasoft.mbg.ems.service.EmsResourceGroupService;
import org.iherus.codegen.utils.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 报警数据Service
 */
@Service
public class SafetyMonitoringService {

    @Value("${photo.path}")
    private  String localhostPath;

    @Resource
    private EmsAlertService emsAlertService;

    @Resource
    private MinIoService minIoService;

    @Resource
    private EmsResourceGroupService emsResourceGroupService;

    @Resource
    private EmsDeployService emsDeployService;




    /**
     * 添加报警数据
     * @param multipartFile 报警图片大图
     * @param multipartFiles 报警图小图
     * @param uid 识别码
     * @return 报警数据
     */
    public EmsAlert create(@NotNull MultipartFile multipartFile, MultipartFile[] multipartFiles,String uid) {
        String resourcePid = null;
        try {
            //上传
            if (multipartFile != null){
                String upload = minIoService.upload(multipartFile);
                if (upload.equals("") || upload.equals(null)){
                    return null;
                }
                //插入到资源组父
                EmsResourceGroup emsResourceGroup = new EmsResourceGroup();
                emsResourceGroup.setId(UUID.randomUUID().toString().replace("-",""));
                emsResourceGroup.setContent(upload);
                emsResourceGroup.setCreateTime(new Date());
                emsResourceGroup.setEnabled(true);
                if (emsResourceGroup.getId() != null){
                    resourcePid = emsResourceGroup.getId();
                }
                emsResourceGroupService.insert(emsResourceGroup);
            }
            //插入到资源组子
            if (multipartFiles.length > 0){
                for (int i = 0;i < multipartFiles.length;i++ ){
                    String upload = minIoService.upload(multipartFiles[i]);
                    //插入到资源组
                    EmsResourceGroup emsResourceGroup = new EmsResourceGroup();
                    emsResourceGroup.setId(UUID.randomUUID().toString().replace("-",""));
                    emsResourceGroup.setPid(resourcePid);
                    emsResourceGroup.setContent(upload);
                    emsResourceGroup.setCreateTime(new Date());
                    emsResourceGroup.setEnabled(true);
                    emsResourceGroupService.insert(emsResourceGroup);
                }
            }
            if (resourcePid != null){
            //根据uid查询
            EmsDeployExample example = new EmsDeployExample();
            EmsDeployExample.Criteria criteria = example.createCriteria();
            if (!StringUtil.isNullOrEmpty(uid)) {
                criteria.andUidEqualTo(uid);
            }
            List<EmsDeploy> list = emsDeployService.selectByExample(example);
            EmsAlert emsAlert = new EmsAlert();
            if (list.size() > 0){
                emsAlert.setDeployId(list.get(0).getId());
            }
            emsAlert.setResourceGroupId(resourcePid);
            emsAlert.setAlertTime(new Date());
            emsAlert.setDescribe("安全监控报警");
            emsAlert.setEnabled(true);
            emsAlert.setCreateTime(new Date());
            emsAlertService.insert(emsAlert);
            return emsAlert;
            }else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }


    }

    /**
     * 下载报警图片
     * @param fileName 报警图片名称
     * @return 报警数据
     */
    public void download(HttpServletResponse response, @NotNull String fileName) {
        try {
            minIoService.download(fileName,response);
        }catch (Exception e){
        }
    }

    public void responseFile(HttpServletResponse response, String path) {
        try {
            byte[] b = FileUtils.readFileToByteArray(new File(path));
            if (b == null) {
                return;
            }
            System.out.println("获取流" + b);
            OutputStream out = response.getOutputStream();
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception var5) {
            System.out.println("当前路径文件读取失败:" + path + var5);
            var5.printStackTrace();
        }

    }


}


Service

package com.sjasoft.cloud.admin.service.ems;

import com.sjasoft.cloud.admin.utils.MinIoUtil;
import com.sjasoft.framework.spring.bean.Result;
import io.minio.ObjectStat;
import org.apache.commons.compress.utils.IOUtils;
import org.iherus.codegen.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * MinIoService

 */
@Service
public class MinIoService {
    @Autowired
    private MinIoUtil minIoUtil;

    @Autowired
    private SafetyMonitoringService safetyMonitoringService;

    @Value("${photo.path}")
    private  String localhostPath;


    /**
     * 下载文件
     */
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        ObjectStat stat = minIoUtil.statObject("", fileName);
        InputStream in = minIoUtil.getObject("", fileName);
        int index;
        byte[] bytes = new byte[1024];
        File filePath = new File(localhostPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        FileOutputStream downloadFile = new FileOutputStream(localhostPath+ "\\" + fileName);
        while ((index = in.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        in.close();
        downloadFile.close();
        File file = new File(localhostPath+ "\\" + fileName);
        if (file.exists() && file.isFile()) {
            safetyMonitoringService.responseFile(response,localhostPath+ "\\" + fileName);
            file.delete();
        }

    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception Exception
     */
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return null;
        } else {
            // 得到文件流
            final InputStream is = file.getInputStream();
            // 文件名
            final String fileName = file.getOriginalFilename();
            // 把文件放到minio的boots桶里面
            minIoUtil.putObject("",fileName,is,-1);
            String objectUrl = minIoUtil.getObjectURL("",fileName);
            // 关闭输入流
            is.close();
            return fileName;
        }
    }

    /**
     * 删除文件
     * @param fileName
     * @return JsonResult
     */
    public Result delete(@RequestParam("fileName") String fileName) throws Exception {
        minIoUtil.removeObject("",fileName);
        return Result.success("删除成功");
    }
}

相关标签: