Maven+SpringMVC项目下的图片压缩上传及跨域访问方法

Maven+SpringMVC项目下的图片压缩上传及跨域访问方法

Dawn
2020-05-17 / 0 评论 / 141 阅读 / 正在检测是否收录...

之前在项目开发中用到了图片上传,当时也是到处找教程,今天将磕磕绊绊得到的方法记录下来,以便以后查看。

一. 图片上传后台相关

1.在pom.xml导入文件上传及文件压缩相关的包

            <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>

        <!-- 文件压缩工具 -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

2.在配置文件里springmvc.xml定义文件上传解析器

        <!-- 定义文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"/>
    </bean>

3.编写图片上传控制器 ImageController.java

    package com.zjq.controller;

    import net.coobird.thumbnailator.Thumbnails;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;

    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;

    @Controller
    public class ImageController {

    /**
     * 上传图片
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/upImage")
    public Map upload(MultipartFile file, HttpServletRequest request){

        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                Date date = new Date();
                //利用时间毫秒来生成图片新名称,避免重名
                String newName = System.currentTimeMillis()+"."+prefix;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateStr = simpleDateFormat.format(date);
                File temppath = new File("C:/");//因为笔者上传到阿里云这里设置的是C盘根目录
                String filepath = temppath.getAbsolutePath()+"image\\" + dateStr+"\\"+newName;

                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                //文件压缩
                MultipartFile oldMultipartFile = file;//记录原MultipartFile,如果压缩异常就用原来的MultipartFile
                try {
                    Thumbnails.of(file.getInputStream())
                            .scale(1f)//尺寸不变
                            .outputQuality(0.30f)//质量变为原来的0.3倍
                            .toFile(files);

                } catch (IOException e) {
                    file = oldMultipartFile;
                    file.transferTo(files);//转存文件
                }

                Map<String,Object> map2=new HashMap<>();
                Map<String,Object> map=new HashMap<>();
                map2.put("src","这里写上面你设置的路径,服务器就是http://域名或IP:端口/image/"+dateStr+"/"+newName);//这里是为了存储数据库
                map.put("code",0);
                map.put("msg","");
                map.put("data",map2);
                return map;
            }

        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("msg","");
        return map;

    }
    }

二. 跨域设置相关

1.在配置文件里springmvc.xml配置接口跨域

        <!-- 接口跨域配置 -->
    <mvc:cors>
        <mvc:mapping path="/**"
                     allowed-origins="*"
                     allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                     allowed-headers="*"
                     allow-credentials="true" />
    </mvc:cors>

2.编写跨域访问过滤器SimpleCORSFilter.java

    package com.zjq.filter;

    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    public class SimpleCORSFilter implements Filter {
    private boolean isCross = false;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (isCross) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            System.out.println("拦截请求: " + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "*");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        isCross = false;
    }
    }

3.在web.xml文件配置跨域请求

        <!-- 跨域请求 -->
    <filter>
        <filter-name>SimpleCORSFilter</filter-name>
        <filter-class>com.zjq.filter.SimpleCORSFilter</filter-class>
        <init-param>
            <param-name>IsCross</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SimpleCORSFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

三. 前端设置相关,页面使用layui

    <%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
    <c:set var="ctx" value="${pageContext.request.contextPath}"/>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="stylesheet" href="${ctx }/layui/css/layui.css" media="all"/>
    <script>
        <%--JS gloable varilible--%>
        var ctx = "${ctx}";
    </script>
    <style type="text/css">
        .layui-form-item .layui-inline {
            width: 33.333%;
            float: left;
            margin-right: 0;
        }

        @media ( max-width: 1240px) {
            .layui-form-item .layui-inline {
                width: 100%;
                float: none;
            }
        }
    </style>
    </head>
    <body class="childrenBody">
    <br/>
    <form class="layui-form" style="width: 80%;" id="aaf">
    <input type="hidden" name="image" class="image"><!-- 用于提交图片路径 -->
    <div class="layui-form-item">
        <label class="layui-form-label ">头像</label>
        <div class="layui-upload">
            <button type="button" class="layui-btn" id="test1">上传图片</button>
            <div class="layui-upload-list">
                <label class="layui-form-label "></label>
                <img class="layui-upload-img" id="demo1" width="80px" height="80px"><!-- 预览图 -->
            </div>
            <label class="layui-form-label"></label>
            <p id="demoText"></p><!-- 提示信息 -->
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit="" lay-filter="addUser">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
    </form>
    <script type="text/javascript" src="${ctx }/layui/layui.js"></script>
    <script>
    var $;
    var form;
    layui.config({
    base: ctx + "/js/"
    }).use(['form', 'layer', 'jquery', 'upload'], function () {
    var layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery,
        form = layui.form,
        upload = layui.upload;

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#test1'
        , url: ctx + '/upImage'
        , accept: 'images'
        , size: 50000
        , before: function (obj) {

            obj.preview(function (index, file, result) {

                $('#demo1').attr('src', result);
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            var demoText = $('#demoText');
            demoText.html('<span style="color: #4cae4c;">上传成功</span>');

            var fileupload = $(".image");
            fileupload.attr("value", res.data.src);
        }
        , error: function () {
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
    form.on("submit(addUser)", function (data) {
        //弹出loading
        var index = layer.load(1, {
            shade: [0.5, '#000']
        });
        $.ajax({
            type: "post",
            url: ctx + "你的注册url",
            data: data.field,
            dataType: "json",
            success: function (d) {
                if (d.code == 0) {
                    layer.close(index);
                    layer.msg("注册成功");
                } else {
                    layer.close(index);
                    layer.msg(d.msg);
                }
            }
        });
        setTimeout(function () {
            parent.location.reload();
        }, 2000);
        return false;
    });
    </script>
    </body>
    </html>

效果图如下:
upimage.png

四. 总结

以上基本就是整体流程及源代码,因为是从整个项目拿下来的一部分,可能会出现某些错误,欢迎提出以便完善,希望这篇文章可以帮助到你!

0

评论 (0)

取消