美文网首页JAVA分布式系统
前后端分离 java后台多图上传,图片压缩,给图片重命名,返回图

前后端分离 java后台多图上传,图片压缩,给图片重命名,返回图

作者: 大卵 | 来源:发表于2019-05-16 18:03 被阅读712次

    这是我呕心沥血从GitHub到码云,各种博客翻烂了,
    写的吐血的劳动成果
    我现在很膨胀~哈哈哈哈哈哈
    今天是个好日子

    用的是这个 MultipartFile 可以了解一下

    废话不多说,现在开始
    这篇文章包含多图上传,多图和单图区别真真不大,图片是放在tomcat
    项目的根目录

    image.png
    技术说因为项目是打成war包
    这样后期方便迁移
    虽然不懂,但技术万岁(≧▽≦)/

    第一步
    我们先去pom引入依赖嘻嘻嘻

    <!--文件上传-->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.2.2</version>
            </dependency>
    
    
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.0.1</version>
            </dependency>
    
    <!--图片压缩了解一下-->
            <dependency>
                <groupId>net.coobird</groupId>
                <artifactId>thumbnailator</artifactId>
                <version>0.4.8</version>
            </dependency>
    

    上controller层 FileUploadController
    这个也没啥用
    反正我没用到过‘
    但是我看到别人都有
    那我也必须有 口亨 😎 可作测试用叭

    package com.asset.controller.backend.base;
    
    
    import com.asset.common.ServerResponse;
    import com.asset.service.base.FileService;
    import com.asset.util.Transform;
    import net.sf.json.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.util.List;
    
    
    /**
     * 基础设置控制
     *
     * @author Administrator
     */
    @RequestMapping("/app")
    @Controller
    public class FileUploadController {
    
        @Autowired
        private FileService fileService;
    
    
        //图片上传  吼吼吼
        @RequestMapping("saveImg.do")
        @ResponseBody
        public ServerResponse saveImg(@RequestParam(value = "file", required = false) MultipartFile[] files,
                                      HttpServletRequest request) {
            String path = request.getSession().getServletContext().getRealPath("/upload/image");
            System.out.println(path);
            List<String> list = fileService.getUploadFile(files, path);
    
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            if (!list.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String s : list) {
                    sb.append("upload/image/" + String.valueOf(s) + ",");
                }
    
                return ServerResponse.createBySuccess(sb);
            }
            return ServerResponse.createByErrorMessage("上传失败");
        }
    
    
        /**
         * 上传临时图片
         */
        @RequestMapping("/settempfile")
        @ResponseBody
        public ServerResponse settempfile(@RequestParam(value = "photos", required = false) MultipartFile[] file,
                                          HttpServletRequest request) {
    
            String savepath = request.getParameter("savepath");
            if (Transform.TestIsEmpty(savepath)) {
                savepath = "upload/temp";
            }
            String path = request.getSession().getServletContext().getRealPath(savepath);
            List<String> files = fileService.getUploadFile(file, path);
            if (null != file) {
                if (!files.isEmpty()) {
                    savepath = savepath + "/" + files.get(0);
                    return ServerResponse.createBySuccess(savepath);
                }
            }
            return ServerResponse.createByErrorMessage("上传失败");
        }
    
    }
    
    

    server层

    package com.asset.service.base;
    
    import org.springframework.web.multipart.MultipartFile;
    
    import java.util.List;
    
    /**
     * @author xyy
     * @date 2019-05-14 16:32
     */
    public interface FileService {
    
        List<String> getUploadFile(MultipartFile[] files, String path);
    }
    
    

    impl实现类

    字体大一号,代表这个是真的有用
    这个里面有对图片重命名 和 对比图片类型
    我把图片压缩也搁在这里了

    package com.asset.service.base.impl;
    
    import com.asset.service.base.FileService;
    import net.coobird.thumbnailator.Thumbnails;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.*;
    
    /**
     * @author xyy
     * @date 2019-05-14 16:37
     */
    @Service("fileService")
    public class FileServiceImpl implements FileService {
    
        public static Set<String> photo;
    
        static {
            photo = new HashSet<String>();
            String[] phototype = {".png", ".jpg", ".jpeg", ".gif", ".bmp"};
            for (String string : phototype) {
                photo.add(string);
            }
        }
    
    
        @Override
        public List<String> getUploadFile(MultipartFile[] file, String savepath) {
            List<String> files = new LinkedList<String>();
    
            try {
                for (MultipartFile multipartFile : file) {
                    String type = multipartFile.getOriginalFilename();
                    System.out.println("type" + type);
                    type = type.substring(type.lastIndexOf("."), type.length());
                    String fileName = NextInt(10000, 99999) + System.currentTimeMillis() + type;
                    File targetFile = new File(savepath, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    // targetFile.delete();
                    // 保存
                    try {
                        multipartFile.transferTo(targetFile);
                        if (multipartFile.getSize() > 100000) {
                            String newfilename = NextInt(10000, 99999) + System.currentTimeMillis() + type;
                            if (photo.contains(type)) {
                                fileName = newfilename;
                            }
                        }
    
                        files.add(fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
    
            }
            return files;
        }
    
        @Override
        public List<String> saveImg(CommonsMultipartFile[] multipartFiles, String path) {
            List<String> files = new LinkedList<String>();
    
            for (CommonsMultipartFile commonsMultipartFile : multipartFiles) {
                String type = commonsMultipartFile.getOriginalFilename();
                if (type != null && type != "") {
                    type = type.substring(type.lastIndexOf("."), type.length());
                    String fileName = NextInt(10000, 99999) + System.currentTimeMillis() + type;
                    File targetFile = new File(path, fileName);
                    if (photo.contains(type)) {
                        try {
                            // 先尝试压缩并保存图片
                            Thumbnails.of(commonsMultipartFile.getInputStream()).scale(1f).outputQuality(0.25f).toFile(targetFile);
                        } catch (IOException e) {
                            try {
    //                        if (!targetFile.exists())
    //                        targetFile.mkdirs();
                                commonsMultipartFile.transferTo(targetFile);
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                    files.add(fileName);
                }
            }
            return files;
        }
    
    
        public static void main(String[] args) {
            String[] phototype = {".png", ".jpg", ".jpeg", ".gif", ".bmp"};
        }
    
        /**
         * 生成随机数
         *
         * @param min
         * @param max
         * @return
         */
        public static int NextInt(final int min, final int max) {
    
            Random rand = new Random();
            int tmp = Math.abs(rand.nextInt());
            return tmp % (max - min + 1) + min;
        }
    
    }
    
    

    接下来是跟项目结合使用

    我要做的是一个app上传多图,显示多图
    尽搞些这花里胡哨的东西 🤨

    image.png

    请注意

    实体类这里 因为传过来的不是只有图片 so~


    image.png

    实现类 不截图了 怕你们懒得打

     @Override
        public ServerResponse saveWorkOrder(WorkOrder workOrder, HttpServletRequest request) {
            if (workOrder.getFid() != null) {
           //path 图片的保存路径  就是存到项目的根目录 
                String path = (new File(request.getServletContext().getRealPath("/"))).getParent() + "/upload" + request.getContextPath() + "/image";
                
                List<String> list = fileService.getUploadFile(workOrder.getPhoto(), path);
                if (!list.isEmpty()) {
                    //存数据库
                    StringBuilder sb = new StringBuilder();
                    for (String s : list) {
                        sb.append("upload" + request.getContextPath() + "/image/" + String.valueOf(s) + ",");
                    }
                    workOrder.setCompleteimg(sb.toString());
                }
                workOrderMapper.updateByPrimaryKeySelective(workOrder);
    
            } else {
                workOrderMapper.insertSelective(workOrder);
            }
            return ServerResponse.createByErrorMessage("保存成功");
        }
    

    纠结了一下还是去给你们打了注解


    image.png

    这一坨细讲


    image.png

    现在已经存进数据库 我们要拿粗来


    image.png

    这是我们拿出来的效果 可以直接访问


    image.png

    取数据库字段拼url

    @Override
        public ServerResponse getImg(Integer fid, HttpServletResponse response) {
            //url 是tomcat项目路径
            String url = MyUtil.getTomcatUrl();
            //通过查询 查存图片的字段
            String img = workOrderMapper.selectImg(fid);
            List<String> imgList = new ArrayList<>();
    //根据逗号分割
            if (!Transform.TestIsEmpty(img)) {
                String[] imgs = img.split(",");
                for (int i = 0; i < imgs.length; i++) {
                    imgList.add(url + imgs[i]);
                }
            }
            return ServerResponse.createBySuccess(imgList);
        }
    

    调用了工具类 拿到tomcat的url

    package com.asset.util;
    
    import com.asset.service.finance.FinPayService;
    import com.asset.vo.request.FinPayManageReqVo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    /**
     * Created by YQY on 2018/10/31.
     */
    public class MyUtil {
        //获取后台项目路径
        public static String getUrl(){
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
            return basePath;
        }
    
        //获取前端路径
        public static String getFrontUrl(){
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            return basePath;
        }
    
        //获取tomcat项目路径
        public static String getTomcatUrl() {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
            return basePath;
        }
    }
    
    

    不想看工具类就看这里叭 就调用了工具类这个方法

    获取tomcat项目路径

     //获取tomcat项目路径
        public static String getTomcatUrl() {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
            return basePath;
        }
    

    不想写了 我累了 突然发现会一样东西不代表可以讲清一样东西

    感jio有点乱 我有时间在整理叭

    对了,题外话’
    用postman测试多图上传
    不能有请求头!!!这是我踩过的坑


    image.png

    相关文章

      网友评论

        本文标题:前后端分离 java后台多图上传,图片压缩,给图片重命名,返回图

        本文链接:https://www.haomeiwen.com/subject/zvniaqtx.html