SpringBoot+Bootstrap 上传图片

文章目录

  • SpringBoot+Bootstrap 上传图片
    • application.yml配置
    • pom.xml文件
    • 上传图片工具类
    • 前端上传图片样式
    • controller 层

SpringBoot+Bootstrap 上传图片

application.yml配置

#配置mysql的连接
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/wyzy?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowMultiQueries=true
    username: root
    password: 123456
  #配置thymeleaf
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML5
    encoding: UTF-8
    servlet:
      content-type: text/html
    cache: false
  servlet:
    multipart:
      enabled: true
      max-file-size: 50MB
      max-request-size: 50MB


  #
  banner.location: classpath:banner.txt
  resources:
    static-locations=classpath:/static/:





pom.xml文件

<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.3.0version>
    dependency>

    <dependency>
        <groupId>com.mysqlgroupId>
        <artifactId>mysql-connector-jartifactId>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>

    
    <dependency>
        <groupId>commons-iogroupId>
        <artifactId>commons-ioartifactId>
        <version>2.4version>
    dependency>


    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poiartifactId>
        <version>3.10-beta2version>
    dependency>


    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxmlartifactId>
        <version>3.10-beta2version>
    dependency>

    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxml-schemasartifactId>
        <version>3.10-beta2version>
    dependency>

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>1.2.62version>
    dependency>

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.16version>
    dependency>
    

dependencies>

上传图片工具类

springboot中 request.getServletContext().getRealPath(“/”) 获取的是一个临时文件夹的地址

package com.jk.zz.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

	//上传图片
	public static String uploadFile(MultipartFile imgfile, HttpServletRequest request){
    	//1、上传路径:项目发布tomcat服务器
        //request.getServletContext().getRealPath(“/”) 获取的是一个临时文件夹的地址
		String path = request.getServletContext().getRealPath("/")+"/upload";
		
		//2、文件
		File file = new File(path);
		if(!file.exists()){//不存在
			file.mkdirs();
		}
		
		//生成新的文件名称,原因:防止文件名称一样后者上传的文件会覆盖前者上传的文件(前提是文件名称必须一样并且在用一个目录下)
		//生成新的文件名称,保证文件名称唯一有两种方法:
		// 	  1.通过UUID实现文件名称唯一 (UUID会生成32位字母+数字唯一的一个字符串)
		//	  2.通过时间戳现文件名称唯一  (时间戳是毫秒级时间 时间会一直往上加,生成13位数字)注意只有java生成13位 其他则是10位比如oracle、mysql、php
		//  获取时间戳
		//long currentTimeMillis = System.currentTimeMillis();
		//System.out.println(currentTimeMillis);
		String uuid = UUID.randomUUID().toString();
		
		String oldName = imgfile.getOriginalFilename();//1.jpg
		//截取文件后缀:.jpg
		String suffix = oldName.substring(oldName.lastIndexOf("."));
		//新文件名
		String newFile = uuid+suffix;
		
		//3、上传
		D:\workUtilsInstall\apache-tomcat-8.0.0\webapps\week_employee_hzy\\upload\1.jpg
		File file2 = new File(path+"\\"+newFile);
		try {
			imgfile.transferTo(file2);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "upload/"+newFile;
	}
	

}

前端上传图片样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入bootstrap的css 文件 -->
    <link rel="stylesheet" href="../js/bootstrap/bootstrap3/css/bootstrap.css">
    <link rel="stylesheet" href="../js/bootstrap/bootstrap3/css/bootstrap-theme.css">


    <!-- 引入jquery文件 -->
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <!-- 引入bootstrap的js文件 -->
    <script type="text/javascript" src="../js/bootstrap/bootstrap3/js/bootstrap.js"></script>

    <!-- 引入tree的js、css文件 -->
    <link rel="stylesheet" href="../js/bootstrap/bootstrap-treeview/bootstrap-treeview.min.css">
    <script type="text/javascript" src="../js/bootstrap/bootstrap-treeview/bootstrap-treeview.min.js"></script>


    <!-- 引入bootbox弹框的css、js文件 -->
    <script type="text/javascript" src="../js/bootstrap/bootstrap-bootbox/bootbox.js"></script>


    <!-- 引入表格的css、js -->
    <link rel="stylesheet" href="../js/bootstrap/bootstrap-table/bootstrap-table.css">
    <script type="text/javascript" src="../js/bootstrap/bootstrap-table/bootstrap-table.js"></script>
    <script type="text/javascript" src="../js/bootstrap/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>


    <!-- 引入上传文件的css、js文件 -->
    <link rel="stylesheet" href="../js/bootstrap/bootstrap-fileinput/css/fileinput.css">
    <script type="text/javascript" src="../js/bootstrap/bootstrap-fileinput/js/fileinput.js"></script>
    <script type="text/javascript" src="../js/bootstrap/bootstrap-fileinput/js/locales/zh.js"></script>

    <!-- 引入选项卡的css、js文件 -->
    <link rel="stylesheet" href="../js/bootstrap/bootStrap-addTabs/bootstrap.addtabs.css">
    <script type="text/javascript" src="../js/bootstrap/bootStrap-addTabs/bootstrap.addtabs.min.js"></script>
</head>
<body>
    <div class="form-group">
        <div class="row">
            <div class="col-md-2"><label>头像:</label></div>
            <div class="col-md-10">
                <!-- name="garbageImg" 自己的封装图片字段 -->
                <input name="garbageImg" id="testimg">
                <input type="file" multiple class="projectfile" accept="image/*" name="headImg" id="headImg">
            </div>
        </div>
    </div>
</body>
<script>
	$(function(){
        uploadImg();
    })
                    
	function uploadImg(url){
        $('#headImg').fileinput({
            initialPreview:url,
            //初始化图片配置:
            initialPreviewConfig: [
                {key: 1, showDelete: false}
            ],
            //是否初始化图片显示
            initialPreviewAsData: true,
            language: 'zh', //设置语言
            uploadUrl: '../wareUser/uploadImg', //上传的地址
            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
            showUpload: true, //是否显示上传按钮
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            maxFileCount: 2, //表示允许同时上传的最大文件个数
            enctype: 'multipart/form-data',
            validateInitialCount:true,
            previewFileIcon: "",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
        }).on('fileuploaded', function(event, data, previewId, index) {
            //alert(data.response);
            alert(location.host)
            var	imgval ="http://"+ location.host+"/"+data.response.path;
            $('#testimg').val(imgval);
        });
    }
</script>
</html>

location.host+“/” http://localhost:8080/

controller 层

@RequestMapping("uploadImg")
public String uploadImg(MultipartFile headImg, HttpServletRequest request){
    String filePath = FileUtil.uploadFile(headImg, request);
    System.out.println("{\"path\":\"" + filePath + "\"}");
    return "{\"path\":\"" + filePath + "\"}";//可以
}

return “{“path”:\”" + filePath + “\”}";

转换成 json 格式 要不然会报错

你可能感兴趣的:(上传图片,bootstrap,java,spring,boot)