下载工具类

package com.wishcome.controller;

import com.wishcome.constants.Constants;
import com.wishcome.domain.SysAdmin;
import com.wishcome.exception.GlobalException;
import com.wishcome.util.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//Arbor 2022/11/16
@RestController
@RequestMapping("/api/pub")
public class DownLoadUtils {

    @Value("${upload.imagesPath}")
    private String imagesPath;

    @Value("${upload.filesPath}")
    private String filesPath;

    @Value("${download.url}")
    private String downloadUrl;

    @Autowired
    private TokenComponent tokenComponent;

    /**
     * 获取文件contentType
     *
     * @param fileExt 文件类型结尾
     * @return
     */
    public static String getContentType(String fileExt) {
        switch (fileExt) {
            case ".doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case ".rtf":
                return "application/rtf";
            case ".xls":
                return "application/vnd.ms-excel";
            case ".xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case ".ppt":
                return "application/vnd.ms-powerpoint";
            case ".pptx":
                return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            case ".pdf":
                return "application/pdf";
            case ".swf":
                return "application/x-shockwave-flash";
            case ".rar":
                return "application/octet-stream";
            case ".zip":
                return "application/x-zip-compressed";
            case ".mp3":
                return "audio/mpeg";
            case ".gif":
                return "image/gif";
            case ".png":
                return "image/png";
            case ".jpeg":
            case ".jpg":
            case ".jpe":
            case ".bmp":
                return "image/jpeg";
            case ".txt":
                return "text/plain";
            case ".svg":
                return " text/xml";
            default:
                return "application/octet-stream";
        }
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param httpServletResponse
     */
    @GetMapping("/files/{filePath}")
    public void downloadLocalFiles(@PathVariable("filePath")String filePath, String fileNameNow, HttpServletResponse httpServletResponse) {
        httpServletResponse.reset();
        /**
         * 如果没有名字(fileNameNow)进行预览,有名字进行下载
         */
        if (!Objects.isNull(fileNameNow)) {
//            fileNameNow = objectName.substring(objectName.lastIndexOf("/") +
            try {
                fileNameNow = URLEncoder.encode(fileNameNow, "UTF-8");
                //设置下载文件的传输类型
                httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileNameNow + "\"");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(filePath.lastIndexOf(".")==-1||filePath.contains("/../")){
            return;
        }
        String fileExt = filePath.substring(filePath.lastIndexOf(".")).trim().toLowerCase();

        InputStream fileInputStream = null;
        OutputStream outStream;

        httpServletResponse.setContentType(getContentType(fileExt));

        // 循环取出流中的数据
        try {
            fileInputStream = new FileInputStream(filesPath + filePath);
            outStream = httpServletResponse.getOutputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outStream.close();
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/images/**")
    public void downloadLocalImages(String filePath, String fileNameNow, HttpServletResponse httpServletResponse) {
        httpServletResponse.reset();
        /**
         * 如果没有名字(fileNameNow)进行预览,有名字进行下载
         */
        if (!Objects.isNull(fileNameNow)) {
//            fileNameNow = objectName.substring(objectName.lastIndexOf("/") +
            try {
                fileNameNow = URLEncoder.encode(fileNameNow, "UTF-8");
                //设置下载文件的传输类型
                httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileNameNow + "\"");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        String fileExt = filePath.substring(filePath.lastIndexOf(".")).trim().toLowerCase();

        InputStream fileInputStream = null;
        OutputStream outStream;

        httpServletResponse.setContentType(getContentType(fileExt));

        // 循环取出流中的数据
        try {
            fileInputStream = new FileInputStream(imagesPath + filePath);
            outStream = httpServletResponse.getOutputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outStream.close();
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("图片上传")
    @PostMapping("/uploadImages")
    public ResponseObject uploadImageFile(MultipartHttpServletRequest request, HttpServletRequest httpServletRequest) {

        String token = httpServletRequest.getHeader(Constants.HEADER_TOKEN_X);
        SysAdmin webAdmin = tokenComponent.getWebAdmin(token);
        if(Objects.isNull(webAdmin)){
            throw new GlobalException(401, "登录过期");
        }
        List<String> objectPaths = new ArrayList<>();
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        multiFileMap.keySet().forEach((key) -> {
            multiFileMap.get(key).forEach((multipartFile) -> {

                if (StringUtils.isEmpty(multipartFile.getOriginalFilename())) return;
                long mb = multipartFile.getSize() / 1024 / 1024;
                if (mb > 2) {
                    throw new GlobalException(709, "图片最大为 2 mb");
                }
                String[] split = multipartFile.getOriginalFilename().split("\\.");
                String originalFilename = System.currentTimeMillis() + "_" + split[0];
                originalFilename = Sha256Util.getSHA256(originalFilename);
                String fileType = split[split.length - 1];
                //bmp/gif/jpg/png
                if (!fileType.equals("bmp") && !fileType.equals("gif") && !fileType.equals("jpg") && !fileType.equals("png") && !fileType.equals("jpeg")) {
                    throw new GlobalException(500, "文件格式不正确");
                }
                originalFilename = originalFilename + "." + fileType;
                String path = imagesPath + File.separator + webAdmin.getId() + File.separator;
                File directory = new File(path);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                path += originalFilename;
                try {
                    BufferedInputStream bis = new BufferedInputStream(multipartFile.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
                    int b;
                    while ((b = bis.read()) != -1) {
                        bos.write(b);
                    }
                    objectPaths.add(downloadUrl + "/api/pub/images/?filePath=" + "/" + webAdmin.getId() + "/" + originalFilename);
                    bos.close();
                    bis.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
        });
        return ResponseObjectUtil.success(objectPaths.size() > 0 ? objectPaths : "");
    }
}


posted @ 2023-03-03 14:39  Arborblog  阅读(17)  评论(0编辑  收藏  举报