zoukankan      html  css  js  c++  java
  • Java实现图片上传、回显、下载

    上传、回显、下载

    package com.gennlife.settlement.rest;
    
    
    import cn.hutool.core.io.FileUtil;
    import cn.hutool.core.io.IoUtil;
    import cn.hutool.core.lang.UUID;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.File;
    import java.io.IOException;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    /**
     * 前端控制器
     * </p>
     *
     * @author author
     * @since 2020-06-29
     */
    @RestController
    @RequestMapping("/settlement")
    public class TGyjhController {
    
        //@Value("${upload.path}")
        private String uploadPath = "config/image/";
    
        /**
         * desc: 单文件上传
         * date: 2019/11/17
         */
        @PostMapping("/uploadOne")
        public Object uploadOne(@RequestParam(value ="file") MultipartFile multipartFile) throws IOException {
            String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String yyyyMMdd = uploadPath + currentDate + File.separator;
            if (!FileUtil.exist(yyyyMMdd)) {
                FileUtil.mkdir(yyyyMMdd);
            }
            String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();
            String suffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
            File file1 = FileUtil.writeBytes(multipartFile.getBytes(), yyyyMMdd + fileName);
            List<Map<String, String>> pathList = new ArrayList<>();
            if (file1.length() > 0) {
                Map<String, String> map = new HashMap<>();
                map.put("fileName", fileName);
                map.put("suffix", suffix);
                map.put("path", yyyyMMdd);
                pathList.add(map);
            }
            return pathList;
        }
    
    
        /**
         * desc: 多文件上传
         * date: 2019/11/17
         */
        @PostMapping("/uploadMany")
        public Object uploadMany(@RequestParam(value ="file")MultipartFile[] file) throws IOException {
            String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String yyyyMMdd = uploadPath + currentDate + File.separator;
            if (!FileUtil.exist(yyyyMMdd)) {
                FileUtil.mkdir(yyyyMMdd);
            }
            List<Map<String, String>> pathList = new ArrayList<>();
    
            if (file.length > 0) {
                for (MultipartFile multipartFile : file) {
                    String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();
    
                    String suffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
    
                    File file1 = FileUtil.writeBytes(multipartFile.getBytes(), yyyyMMdd + fileName);
    
                    if (file1.length() > 0) {
                        Map<String, String> map = new HashMap<>();
                        map.put("fileName", fileName);
                        map.put("suffix", suffix);
                        map.put("path", currentDate);
                        pathList.add(map);
                    }
                }
            }
            return pathList;
        }
    
    
        /**
         * desc: 图片显示
         * date: 2019/11/17
         */
        @PostMapping("showImg")
        public Object showImg(HttpServletResponse response, @RequestBody Map<String, Object> map) {
            if (map.isEmpty()) {
                return "文件不能为空";
            }
            boolean suffix = checkPic(map.get("suffix").toString());
            if (!suffix) {
                return "不是图片";
            }
            try {
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(FileUtil.readBytes(map.get("path").toString() + map.get("fileName").toString()));
                IoUtil.close(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
        /**
         * desc: 文件下载
         * date: 2019/11/17
         */
        @PostMapping("download")
        public Object download(HttpServletResponse response, @RequestBody Map<String, Object> map) throws IOException {
            if (map.isEmpty()) {
                return "文件不能为空";
            }
            String fileUrl = uploadPath + map.get("path").toString() + File.separator + map.get("fileName").toString();
            //        String suffix = map.get("suffix").toString();
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/force-download");
            //        设置编码,避免文件名中文乱码
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(map.get("fileName").toString().getBytes("gb2312"), "ISO8859-1"));
            outputStream.write(FileUtil.readBytes(fileUrl));
            IoUtil.close(outputStream);
            return null;
        }
    
    
        /**
         * desc: 图片格式检验
         * date: 2019/11/17
         */
        private static boolean checkPic(String suffix) {
            if (suffix.isEmpty()) {
                return false;
            }
            String reg = "(.JPEG|.jpeg|.JPG|.jpg|.PNG|.png|.GIF|.gif|.BMP|.bmp)$";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher("." + suffix);
            return matcher.find();
        }
    }
    
  • 相关阅读:
    使用Visual Studio 2010来部署Windows应用程序
    如何显示一个非激活窗体
    构建ASP.NET网站十大必备工具(2)
    在Azure中创建一个“Hello World”应用程序
    轻松搞定VS2010 和旧版本服务器一起使用的问题
    Sql注入与转义
    小数型 Float(M,D),decimal(M,D)
    MySQL SQL语句
    作业综合练习配置+自定义函数设置
    作业综合练习初始化工作
  • 原文地址:https://www.cnblogs.com/dyaqi/p/14966872.html
Copyright © 2011-2022 走看看