SpringBoot 通过 bootstrapFileinput 多文件上传

avatar 2021年03月05日10:55:19 6 5420 views
博主分享免费Java教学视频,B站账号:Java刘哥

前几天朋友让在初云博客上加一个相册功能,现在就开始做!

前端上传组件选择 bootstrapFileinput,该插件支持批量上传和拖拽上传。

 

直接上代码

一、下载  bootstrap-fileinput

官网地址:https://github.com/kartik-v/bootstrap-fileinput

直接克隆或下载zip,解压重命名文件夹为 bootstrap-fileinput

放到项目中

二、前端代码

1. 引入css和js文件

<link rel="stylesheet" href="/static/plugins/bootstrap-fileinput/css/fileinput.min.css">
  
<script src="/static/plugins/bootstrap-fileinput/js/fileinput.min.js"></script>
<script src="/static/plugins/bootstrap-fileinput/js/locales/zh.js"></script>

注意:除此之外,需要引入 bootstrap 和 jquery 相关的 css 和 js

 

2.HTML代码

<form>
    <div>
        <div class="modal-header">
            图片上传
        </div>
        <div class="modal-body">
            <input type="file" name="file" id="file" multiple class="file-loading"/>
        </div>
    </div>
</form>

 

3. JS代码

<script>
    $(function () {
	    var control = $("#file");
	    // var cateId = [[${photoCategory.id}]];
	    // var uploadrul = "/admin/photo/upload?cateId=" + cateId; // 上传到具体的相册,大家可以忽略
	    var uploadUrl = "/admin/photo/upload";
	    control.fileinput({
	        language: 'zh', //设置语言
	        uploadUrl: uploadUrl, //上传的地址
	        allowedFileExtensions: ['png', 'jpeg', 'jpg', 'gif'],//接收的文件后缀
	        showUpload: true, //显示批量上传按钮
	        showCaption: false,//是否显示标题
	        browseClass: "btn btn-primary", //按钮样式
	        dropZoneEnabled: true,//是否显示拖拽区域
	        //minImageWidth: 50, //图片的最小宽度
	        //minImageHeight: 50,//图片的最小高度
	        //maxImageWidth: 1000,//图片的最大宽度
	        //maxImageHeight: 1000,//图片的最大高度
	        maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
	        minFileCount: 0,
	        maxFileCount: 100,
	        enctype: 'multipart/form-data',
	        validateInitialCount: true,
	        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",

	        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
	    });
	    //导入文件上传完成之后的事件
	    $("#file").on("fileuploaded", function (event, data, previewId, index) {
	        //showMsgAndReload("上传成功", "success", 1000);
	        alert('上传成功');
	        window.location.reload();
	    });
	});
</script>

 

三、java 后端代码

后端是基于 springboot (或springmvc)  的

1、控制器代码

/**
 * 照片上传
 *
 * @param file 文件
 * @return JsonResult
 */
@PostMapping(value = "/admin/photo/upload")
@ResponseBody
public JsonResult uploadFile(@RequestParam("file") MultipartFile file) {
    Map<String, String> resultMap = FileUtil.upload(file);
    // 其他操作,如存储文件信息到数据库
    return JsonResult.success("上传成功");
}

选择多个文件,实际前端会发送多个请求

具体照片其他操作,我这里就不贴了

 

 

2、文件上传工具类代码

package com.example.forum.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrBuilder;
import com.example.forum.enums.CommonParamsEnum;
import com.example.forum.exception.MyBusinessException;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传根据类
 *
 * @author 言曌
 * @date 2020/3/8 5:45 下午
 */
public class FileUtil {


    /**
     * 文件上传
     * 上传图片和缩略图
     *
     * @param file
     * @return
     */
    public static Map<String, String> upload(MultipartFile file) {
        final Map<String, String> resultMap = new HashMap<>(6);
        try {
            //用户目录
            final StrBuilder uploadPath = new StrBuilder(System.getProperties().getProperty("user.home"));
            uploadPath.append("/sens/upload/" + DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
            final File mediaPath = new File(uploadPath.toString());
            if (!mediaPath.exists()) {
                if (!mediaPath.mkdirs()) {
                    throw new MyBusinessException("文件上传失败,无法创建文件夹");
                }
            }
            // 原始文件名
            String originFileName = file.getOriginalFilename();
            // 后缀
            final String fileSuffix = originFileName.substring(file.getOriginalFilename().lastIndexOf('.') + 1);
            // 新文件名
            String nameWithOutSuffix = UUID.randomUUID().toString().replaceAll("-", "");

            //带后缀
            String newFileName = nameWithOutSuffix + "." + fileSuffix;
            String newSmallFileName = nameWithOutSuffix + "_small." + fileSuffix;

            // 判断文件名是否已存在
            File descFile = new File(mediaPath.getAbsoluteFile(), newFileName.toString());
            file.transferTo(descFile);

            // 文件原路径
            final StrBuilder fullPath = new StrBuilder(mediaPath.getAbsolutePath());
            fullPath.append("/");
            fullPath.append(newFileName);

            // 缩略图路径
            final StrBuilder fullSmallPath = new StrBuilder(mediaPath.getAbsolutePath());
            fullSmallPath.append("/");
            fullSmallPath.append(newSmallFileName);

            //压缩图片
            try {
                Thumbnails.of(fullPath.toString()).size(256, 256).keepAspectRatio(false).toFile(fullSmallPath.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }

            //映射路径
            final StrBuilder filePath = new StrBuilder("/upload/");
            filePath.append(DateUtil.thisYear());
            filePath.append("/");
            filePath.append(DateUtil.thisMonth() + 1);
            filePath.append("/");
            filePath.append(nameWithOutSuffix + "." + fileSuffix);

            //缩略图映射路径
            final StrBuilder fileSmallPath = new StrBuilder("/upload/");
            fileSmallPath.append(DateUtil.thisYear());
            fileSmallPath.append("/");
            fileSmallPath.append(DateUtil.thisMonth() + 1);
            fileSmallPath.append("/");
            fileSmallPath.append(nameWithOutSuffix);
            fileSmallPath.append("_small.");
            fileSmallPath.append(fileSuffix);

            final String size = parseSize(new File(fullPath.toString()).length());
            final String wh = getImageWh(new File(fullPath.toString()));

            resultMap.put("fileName", originFileName);
            resultMap.put("filePath", filePath.toString());
            resultMap.put("fileSmallPath", fileSmallPath.toString());
            resultMap.put("fileSuffix", fileSuffix);
            resultMap.put("fileSize", size);
            resultMap.put("fileWh", wh);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyBusinessException("文件上传失败");
        }
        return resultMap;
    }


    /**
     * 转换文件大小
     *
     * @param size size
     * @return String
     */
    private static String parseSize(long size) {
        if (size < CommonParamsEnum.BYTE.getValue()) {
            return size + "B";
        } else {
            size = size / 1024;
        }
        if (size < CommonParamsEnum.BYTE.getValue()) {
            return size + "KB";
        } else {
            size = size / 1024;
        }
        if (size < CommonParamsEnum.BYTE.getValue()) {
            size = size * 100;
            return (size / 100) + "." + (size % 100) + "MB";
        } else {
            size = size * 100 / 1024;
            return (size / 100) + "." + (size % 100) + "GB";
        }
    }


    /**
     * 获取文件长和宽
     *
     * @param file file
     * @return String
     */
    private static String getImageWh(File file) {
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(file));
            return image.getWidth() + "x" + image.getHeight();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

 

 

3、图片压缩的依赖 

pom.xml

<!-- 图片操作 -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

 

4、图片显示,静态资源映射

package com.example.forum.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器,资源路径配置
 */
@Slf4j
@Configuration
@EnableWebMvc
public class MvcConfig implements  WebMvcConfigurer  {


    /**
     * 配置静态资源路径
     *
     * @param registry registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        
        // 映射upload文件夹下的照片到 /upload
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:///" + System.getProperties().getProperty("user.home") + "/sens/upload/");

    }

    
}

 

四、效果图

效果图如下

 

文件上传位置在用户目录/sens/upload/年/月 里

windows用户在 C盘下的用户文件夹里,如 C:\\用户\\LIUYANZHAO\\sens\\upload 里 (LIUYANZHAO是计算机名称

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0