记录一次springboot+layui图片上传

 

1.application.properties文件默认,可以用不用配置。

2.启动类自动生成。

3.编写UploadFileController类

package com.shenk.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.shenk.common.Constant;
import com.shenk.common.ResultReturn;
import com.shenk.common.ResultReturnUtil;

@Controller
public class UploadFileController {
	@RequestMapping("/upload")
	public String upload() {
		return "upload";
	}
    @RequestMapping("/uploadFile")
    @ResponseBody
    public ResultReturn uploadFile(MultipartFile file, HttpServletRequest request) {
        String filePath = "D:/upload/";//上传到这个文件夹
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String finalFilePath = filePath + file.getOriginalFilename().trim();
        File desFile = new File(finalFilePath);
        if (desFile.exists()) {
            desFile.delete();
        }
        try {
            file.transferTo(desFile);
            return ResultReturnUtil.success(Constant.UPLOAD_SUCCESS);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResultReturnUtil.fail(Constant.UPLOAD_FAIL);
        }
    }
}

4.编写MyWebStaticConfig类

package com.shenk.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 	静态资源映射
 * @author Administrator
 *
 */
@Configuration
public class MyWebStaticConfig implements WebMvcConfigurer {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String pathPatterns = "/pictures/**";
        String pathAbsolute= "file:D:/upload/";
        //addResoureHandler:指的是对外暴露的访问路径
        //addResourceLocations:指的是内部文件放置的目录
        //通过设置spring.resources.static-locations自定义Spring boot加载前端静态资源路径
//        如果指定了拦截器,该属性有可能失效
//        需要在拦截器ResourceHandlerRegistry中通过addLocations()指定对应路径

        registry.addResourceHandler(pathPatterns).addResourceLocations(pathAbsolute);
	}

}

5.编写Constant类

package com.shenk.common;

public class Constant {
 
//  数据上传成功返回信息
    public static final String UPLOAD_SUCCESS = "文件上传成功!";
 
//	数据上传失败返回信息
    public static final String UPLOAD_FAIL = "文件上传失败";
 
}

6.编写ResultReturn类

package com.shenk.common;

import java.io.Serializable;

public class ResultReturn implements Serializable {
 
    private static final long serialVersionUID = 5805792987639183304L;
    /**
     * 0成功  -1失败
     */
    private String code;
 
    private String msg;
 
    private Object data;
 
    
 
    public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public ResultReturn(){
        super();
    }
 
    public ResultReturn(String code, String msg){
        this.code = code;
        this.msg = msg;
    }
 
    public ResultReturn(String code, String msg, Object data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}

7.编写ResultReturnUtil类

package com.shenk.common;

public class ResultReturnUtil {
 
    /**
     *	 成功 返回自定义提示信息
     * @param msg
     * @return
     */
    public static ResultReturn success(String msg){
        return new ResultReturn("0",msg);
    }
 
    /**
     * 	成功  返回自定义码和提示消息
     * @param code
     * @param msg
     * @return
     */
    public static ResultReturn success(String code, String msg){
        return new ResultReturn(code,msg);
    }
    /**
     * 	成功 返回自定义提示信息和数据
     * @param msg
     * @param data
     * @return
     */
    public static ResultReturn success(String msg, Object data){
        return  new ResultReturn("0",msg,data);
    }
    /**
     * 	失败 返回自定义提示信息
     * @param msg
     * @return
     */
    public static ResultReturn fail(String msg){
        return new ResultReturn("-1",msg);
    }
    /**
     * 	失败 返回自定义码和提示信息
     * @param code
     * @param msg
     * @return
     */
    public static ResultReturn fail(String code, String msg){
        return new ResultReturn(code,msg);
    }
}

8.编写upload页面。页面需要引入layui的相关包。

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传</title>
<link rel="stylesheet" href="/layui/css/layui.css" />
<script src="/layui/layui.js" charset="utf-8"></script>
</head>
<body>
    <div class="layui-upload">
        <button type="button" class="layui-btn" id="test1"><i class="layui-icon">&#xe67c;</i>选择文件</button>
        <button type="button" class="layui-btn" id="test9">开始上传</button>
        <div id="appenDemo"></div>
        <div id="demoText"></div>     
        <div>
            <img th:src="@{/pictures/}+展示2.png" style="height: 240px;">
        </div>
    </div>
    
    <script>
    layui.use('upload', function(){
          var $ = layui.jquery
          ,upload = layui.upload;
          
          //普通图片上传
          var uploadInst = upload.render({
            elem: '#test1'
            ,url: 'uploadFile' //改成自己的上传接口
            ,auto: false//不自动上传
            ,bindAction: '#test9'
            ,choose: function (obj) {
               //将每次选择的文件追加到文件队列
                var files = obj.pushFile();
               //预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
                obj.preview(function (index, file, result) {
                	$('#appenDemo').empty();
                    $('#fileName').val(file.name);  //展示文件名
                    $('#appenDemo').append('<div class="image-container" id="container'+index+'"><div><button id="upload_img_'+index+'" class="layui-btn layui-btn-danger layui-btn-xs">删除</button></div>' +
                                '<img id="showImg'+index+'" style="width: 150px;cursor:pointer;"src="' + result + '" alt="' + file.name + '"></div>');
	                //删除某图片
	                $("#upload_img_" + index).bind('click', function () {
	                    delete files[index];
	                    $("#container"+index).remove();
	                    $('#appenDemo').empty();
	                });
	                //图片放大预览
	                $("#showImg"+index).bind('click',function () {
	                    var width = $("#showImg"+index).width();
	                    var height = $("#showImg"+index).height();
	                    var scaleWH = width/height;
	                    var bigH = 600;
	                    var bigW = scaleWH*bigH;
	                    if(bigW>900){
	                        bigW = 900;
	                        bigH = bigW/scaleWH;
	                    }
	                    layer.open({
	                        type: 1,
	                        title: false,
	                        closeBtn: 1,
	                        shadeClose: true,
	                        area: [bigW + 'px', bigH + 'px'], //宽高
	                        content: "<img width='"+bigW+"' height='"+bigH+"' src=" + result + " />"
	                    });
	                });
                })
            }
            ,done: function(res){
              //如果上传失败
              if(res.code < 0){
                return layer.msg(res.msg);
              } else{
                  $('#appenDemo').empty();
                  $('#demoText').empty();
                  return layer.msg(res.msg);
              }
              //上传成功
            }
            ,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();
              });
            }
          });
    });
</script>
</body>
</html>

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值