SpringBoot+Tyhmeleaf+文件上传

本文介绍了如何在SpringBoot项目中结合Tyhmeleaf实现文件上传功能,详细阐述了从引入上传工具包,创建文件实体,设计HTML页面到控制器层处理的完整流程。
摘要由CSDN通过智能技术生成

文件上传功能的开发流程

思路:
①引入“文件上传”功能的工具包;
②添加文件实体domain–Files;
③Html页面的使用方法;
④Controller层的调用方法

步骤:
1.引入“文件上传”功能的工具包
(文件上传的路径及其命名规则都封装在了这几个工具包内)
在这里插入图片描述

package com.***.util;
public class bConst1 {
    // 验证码
    public static final String SESSION_SECURITY_CODE = "sessionSecCode";
    // session用的用户
    public static final String SESSION_USER = "sessionUser";
    public static final String SESSION_MENU_RIGHTS = "sessionMenuRights";
    // 当前菜单
    public static final String SESSION_menuList = "menuList";
    // 当前菜单
    public static final String SESSION_allmenuList = "allmenuList";
    // 未登录时的菜单
    public static final String SESSION_nousermenuList = "nousermenuList";
    // 修改权限
    public static final String SESSION_QX = "QX";
    // 用户ID
    public static final String SESSION_USERID = "SX_USERID";
    // 用户名
    public static final String SESSION_UNAME = "SX_UNAME";
    // 登陆名
    public static final String SESSION_USERNAME = "SX_USERNAME";
    // 用户角色
    public static final String SESSION_USERROLEID = "SX_USERROLEID";
    // 用户所管理的所有下属区域列表(用户管理用)
    public static final String SESSION_USERAREALIST = "USERAREALIST";
    // 用户所管理的区域及所有下属区域列表(经纬度信息管理用)
    public static final String SESSION_MAPAREALIST = "MAPAREALIST";
    public static final String TRUE = "T";
    public static final String FALSE = "F";

    // 文件路径
    public static final String FILEPATH = "uploadFiles/";
    // 图片上传路径
    //	public static final String FILEPATHIMG = "uploadFiles/uploadImgs/";
    // 系统文件路径
    public static final String FILEPATHFILE = "uploadFiles/file/";
    // 系统文件路径
    public static final String FILEPATHBACKIMAGE = "uploadFiles/file/backimage/";
    //申请文件上传路径
    public static final String FILEPATHAPPLY = "uploadFiles/applyfile/";
    //导出节目excel文件压缩包临时文件夹
    public static final String FILEPATHPROTEMP = "uploadFiles/protemp/";
    //特种节目文件夹
    public static final String FILEPATHPROSPEC = "uploadFiles/audiofile/prospec/";
    //节目文件夹
    public static final String FILEPATHPER = "uploadFiles/audiofile/";

    public static final String[] LOGTYPE=new String[]{"登陆日志","操作日志"};

    public static final String SHOWTEXT = "SHOWTEXT";
}
package com.***.util;

//常量
public class bConstant1 {
    /** 文件上传/图片   根目录 */
    public static final String UPLOAD_PATH = System.getProperty("user.home") + "/upload/"; //bConst1.FILEPATHPER

    /** 图片目录 */
    public static final String IMG_FILE_NAME = "img";

    /** 图片相对路径 */
    public static final String VIRTUAL_IMG_PATH = "img/virtual";
}

package com.***.util;
import com.ruoyi.village.domain.Files;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

public class bFileUtil1 {
    private static Logger logger = LoggerFactory.getLogger(bFileUtil1.class);
    /**
     * 图片存储 完整路径({user.home}/img/coldStone/XXX.jpg)
     * @param file
     * @return 返回相对路径
     */
    public static String saveImg(MultipartFile file,String saveName) {
        //获取文件上传的根目录 C:\Users\fama/upload/img
        String  path = bConstant1.UPLOAD_PATH + bConstant1.IMG_FILE_NAME; //改为bConstant.UPLOAD_PATH

        //拿到文件的后缀名和UUID进行拼接形成新的文件名
        //4ca64e85b1544c96b4a6154bb521476f.jpg
        //String saveName = bCommonUtil.getUuid() + "." + getFileSuffix(file.getOriginalFilename());
        logger.info(" --- 文件保存路径:{}, 文件保存名称:{},文件原名称:{} --- ", path, saveName,file.getOriginalFilename());

        // 保存
        try {
            // 保存文件图片
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            file.transferTo(new File(path + "/" + saveName));
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("--- 文件保存异常:{} ---" + e.getMessage());
            return null;
        }
        String filePath =  bConstant1.UPLOAD_PATH;;
        //返回相对路径  img/virtual/4ca64e85b1544c96b4a6154bb521476f.jpg
        return saveName; //filePath + "/" + saveName
    }
    /**
     * 返回截取的文件后缀
     * @param path
     * @return
     */
    public static String getFileSuffix(String path) {
        return getFileSuffix(path, "2");
    }

    /**
     * 获取文件名称或后缀(最后一个"."之后内容)
     * @param path
     * @param type 1名称 2后缀
     * @return
     */
    public static String getFileSuffix(String path, String type){
        if(StringUtils.isNotEmpty(path) && path.indexOf(".") > 0) {
            // 名称
            String name = path.substring(0, path.lastIndexOf("."));

            // 后缀
            String suffix = path.substring(path.lastIndexOf(".") + 1);

            return StringUtils.equals("1", type) ? name : suffix;
        } else {
            return null;
        }
    }

    /**
     * 文件上传封装
     * @param maxfileid
     * @param file
     * @param fname
     * @param flenth
     * @param fsize
     * @param year
     * @return Program
     */
    public static com.ruoyi.village.domain.Files uplodeFile(String maxfileid, MultipartFile file, String fname, String flenth, String fsize, String year){
        Files g = new Files();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        /*int fileid = 0;
        if(maxfileid!=null&& Integer.parseInt(maxfileid)>10){
            fileid = Integer.parseInt(maxfileid);
        }else{
            fileid = 1;
        }*/
        int j=0; //上传多个的时候用的
        String filename ="";
        String failfile="";//添加失败的节目
        if(file!=null ){
            filename = maxfileid+j+"";
            while(filename.length()<5){
                filename = "0"+filename;
            }
            filename = year.substring(2)+filename;
            if (null != file && !file.isEmpty()) {
                filename =filename+"."+bFileUtil1.getFileSuffix(file.getOriginalFilename()); //filename字段
                if(flenth!="NaN"&&!flenth.equals("")){
//                    Double lenth = Double.parseDouble(flenth)*1000;
//                    String l = DateUtil.formatLongToTimeStr(lenth.longValue());
//                    g.setFlenth(l);
                    //System.out.println("flenth:--"+flenth);
                    g.setFlenth(flenth);
                }else{
                    failfile = fname+"获取时长信息出错,";
                }
                //System.out.println("fname:--"+fname);
                g.setFname(fname); //fname.substring(0, fname.lastIndexOf("."))
                //String filePath = bPathUtil1.getClasspath() + bConst1.FILEPATHPER;			//文件上传路径
                String path =  bFileUtil1.saveImg(file,filename);//
                //System.out.println("filename:--"+filename);
                g.setFilename(filename);
                //System.out.println("Userid:--"+bJurisdiction.getUserid()); //有错误///
                //g.setUserid(bJurisdiction.getUserid());
                //System.out.println("Address:--"+bPathUtil1.getClasspath() + bConst1.FILEPATHPER+path);
                g.setAddress(bPathUtil1.getClasspath() + bConst1.FILEPATHPER+path);
                //System.out.println("Urls:--"+bConst1.FILEPATHPER+path);
                g.setUrls(bConst1.FILEPATHPER+path);
                //System.out.println("Createdtime:--"+df.format(new Date()));
                g.setCreatedtime(df.format(new Date()));
                g.setIspublic(false);
                g.setIslisten(true);
                if(fsize!=null&&!fsize.equals("")){
                    BigDecimal b   =   new   BigDecimal(fsize);
                    g.setFsize(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue() );//四舍五入 两位小数
                }
                j++;
            }

        }
        return g;
    }
}

package com.***.util;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

public class bPathUtil1 {

    /**
     * 图片访问路径
     * @param pathType
     *            图片类型 visit-访问;save-保存
     * @param pathCategory
     *            图片类别,如:话题图片-topic、话题回复图片-reply、商家图片
     * @return
     */
    public static String getPicturePath(String pathType, String pathCategory) {
        String strResult = "";
        StringBuffer strBuf = new StringBuffer();
        if ("visit".equals(pathType)) {
        } else if ("save".equals(pathType)) {
            String projectPath = bPublicUtil1.getPorjectPath().replaceAll("\\\\",
                    "/");
            projectPath = splitString(projectPath, "bin/");
            strBuf.append(projectPath);
            strBuf.append("webapps/ROOT/");
        }
        strResult = strBuf.toString();
        return strResult;
    }

    private static String splitString(String str, String param) {
        String result = str;

        if (str.contains(param)) {
            int start = str.indexOf(param);
            result = str.substring(0, start);
        }

        return result;
    }

    /**获取classpath1
     * @return
     */
    public static String getClasspath(){
        String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../../").replaceAll("file:/", "").replaceAll("%20", " ").trim();
        if(path.indexOf(":") != 1){
            path = File.separator + path;
        }
        return path;
    }

    /**获取classpath2
     * @return
     */
    public static String getClassResources(){
        String path =  (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
        if(path.indexOf(":") != 1){
            path = File.separator + path;
        }
        return path;
    }
    public static void main(String[] args) {
        System.out.println(getClassResources());
    }
    public static String PathAddress() {
        String strResult = "";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();

        StringBuffer strBuf = new StringBuffer();
        strBuf.append(request.getScheme() + "://");
        strBuf.append(request.getServerName() + ":");
        strBuf.append(request.getServerPort() + "");
        strBuf.append(request.getContextPath() + "/");
        strResult = strBuf.toString();// +"ss/";//加入项目的名称
        return strResult;
    }

}

package com.***.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
public class bPublicUtil1 {

    public static void main(String[] args) {
//		System.out.println("本机的ip=" + PublicUtil.getIp());
    }

    public static String getPorjectPath(){
        String nowpath = "";
        nowpath=System.getProperty("user.dir")+"/";

        return nowpath;
    }

    /**
     * 获取本机访问地址
     * @return
     */
    public static String getIp(){
        String ip = "";
        try {
            InetAddress inet = InetAddress.getLocalHost();
            ip = inet.getHostAddress();
            //System.out.println("本机的ip=" + ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return ip;
    }

}

2.添加文件实体domain——>Files
在这里插入图片描述

package com.***.domain;
import com.***.common.base.BaseEntity;
public class Files extends BaseEntity {
	private static final long serialVersionUID = 1L;

	private String fid;//节目申请-节目ID
	private String fname;//节目名称
	private String userid;//用户ID
	private String remark;//备注
	private Boolean ispublic;//是否公共
	private String filename;//要求文稿名
	private String address;//要求文稿路径
	private String urls;//要求文稿路径
	private String createdtime;//申请提交时间
	private String flenth;//节目时长
	private Double fsize;//文件大小
	private Boolean islisten;//是否审听
	private Boolean ptype;//节目类型,是否是录制节目
	private String uname;//上传用户名

	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getFid() {
		return fid;
	}
	public void setFid(String fid) {
		this.fid = fid;
	}
	public String getFname() {
		return fname;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public Boolean getIspublic() {
		return ispublic;
	}
	public void setIspublic(Boolean ispublic) {
		this.ispublic = ispublic;
	}

	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public String getUrls() {
		return urls;
	}
	public void setUrls(String urls) {
		this.urls = urls;
	}
	public String getCreatedtime() {
		return createdtime;
	}
	public void setCreatedtime(String createdtime) {
		this.createdtime = createdtime;
	}
	public String getFlenth() {
		return flenth;
	}
	public void setFlenth(String flenth) {
		this.flenth = flenth;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Boolean getPtype() {
		return ptype;
	}
	public void setPtype(Boolean ptype) {
		this.ptype = ptype;
	}
	public Boolean getIslisten() {
		return islisten;
	}
	public void setIslisten(Boolean islisten) {
		this.islisten = islisten;
	}
	public Double getFsize() {
		return fsize;
	}
	public void setFsize(Double fsize) {
		this.fsize = fsize;
	}

	@Override
	public String toString() {
		return "Program{" +
				"fid='" + fid + '\'' +
				", fname='" + fname + '\'' +
				", userid='" + userid + '\'' +
				", remark='" + remark + '\'' +
				", ispublic=" + ispublic +
				", filename='" + filename + '\'' +
				", address='" + address + '\'' +
				", urls='" + urls + '\'' +
				", createdtime='" + createdtime + '\'' +
				", flenth='" + flenth + '\'' +
				", fsize=" + fsize +
				", islisten=" + islisten +
				", ptype=" + ptype +
				", uname='" + uname + '\'' +
				'}';
	}
}

3.Html页面的使用方法
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

<!DOCTYPE HTML>
<html  lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="multipart/form-data;charset=utf-8" />
<link th:href="@{/css/plugins/dropzone/basic.css}" rel="stylesheet">
<link th:href="@{/css/plugins/dropzone/dropzone.css}" rel="stylesheet">

<head th:include="include :: header"></head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-filemanager-add" enctype="multipart/form-data" th:action="@{add}" method="post">
        <div class="form-group">
            <label class="col-sm-3 control-label">项目上传:</label>
            <div class="col-sm-8">
                <input id="files" name="files" class="form-control" type="file">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">文件时长:</label>
            <div class="col-sm-8">
                <input id="flenth" name="flenth" class="form-control" type="text" hidden readonly value="">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">文件大小:</label>
            <div class="col-sm-8">
                <input id="fsize" name="fsize" class="form-control" type="text" hidden readonly value="">
            </div>
        </div>
    </form>
</div>
<div th:include="include::footer"></div>
<script type="text/javascript">
    var prefix = ctx + "village/project"
    // 检测是否选择文件,如果选择,返回文件对象;如果没选择,返回false
    function checkFile(){
        // 获取文件对象(该对象的类型是[object FileList],其下有个length属性)
        var fileList = $('#files')[0].files;

        // 如果文件对象的length属性为0,就是没文件
        if (fileList.length === 0) {
            console.log('没选择文件');
            return false;
        };
        return fileList[0];
    };
    function aa(){
        let  file = checkFile();
        let size = file.size;
        console.log("文件大小",size);
        //获取录音时长
        let url = URL.createObjectURL(file);
        let audioElement = new Audio(url);
        let duration = audioElement.duration/60; //音频长度 视频不行
        $("#flenth").attr("value",duration);
        $("#fsize").attr("value",size);
        console.log(duration,size)
    };
    function submitHandler() {
        if (!checkFile()) {
            alert('请先选择文件');
            return false;
        }
        else {
            aa();
            $.modal.loading("正在上传中,请稍后...");
            $(function () {
                /** 验证文件是否导入成功  */
                $("#form-filemanager-add").ajaxSubmit(function (data) {
                    $.operate.successCallback({"code": data.code, "msg": data.msg});
                    //alert("post success." + data.code+"--"+data.msg);
                });
                return false;
            });
        }
    }
    function sleep(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }
</script>
<script>
    $(document).ready(function(){Dropzone.options.myAwesomeDropzone={autoProcessQueue:false,uploadMultiple:true,parallelUploads:100,maxFiles:100,init:function(){var myDropzone=this;this.element.querySelector("button[type=submit]").addEventListener("click",function(e){e.preventDefault();e.stopPropagation();myDropzone.processQueue()});this.on("sendingmultiple",function(){});this.on("successmultiple",function(files,response){});this.on("errormultiple",function(files,response){})}}});
</script>
<script th:src="@{/js/plugins/dropzone/dropzone.js}"></script>
<script th:src="@{/js/jquery-form.js}"></script>
</body>
</html>

4.Controller层的调用方法
在这里插入图片描述
在这里插入图片描述

package com.***.web.controller.***;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.ruoyi.village.util.bFileUtil1;
import com.ruoyi.common.utils.DateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.village.domain.Project;
import com.ruoyi.village.domain.Files;
import com.ruoyi.village.service.IProjectService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/village/project")
public class ProjectController extends BaseController
{
	private String prefix = "village/project";

	/**
	 * 新增重大项目
	 */
	@GetMapping("/add")
	public String add()
	{
		return prefix + "/add";
	}

	/**
	 * 新增保存重大项目
	 */
	@Log(title = "新增项目", businessType = BusinessType.INSERT)
	@PostMapping(value = "/add")
	@ResponseBody
    /*这里加入Project project是为了获得html页面form返回来的数据*/
	public AjaxResult addSave(Project project,@RequestParam(value = "files") MultipartFile file,
							  @RequestParam(value = "filename", required = false) String fname,
							  @RequestParam(value = "flenth" ,required = false)String flenth, //时长
							  @RequestParam(value = "fsize",required = false) String fsize){//大小
		String year = DateUtil.getYear();

		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss");
		System.out.println(dateFormat.format(date));
		String maxfileid = dateFormat.format(date); //获取文件上传时的时间参数字符串作为文件名

        //图片上传调用工具类
		try{
			//保存图片
			Files g = bFileUtil1.uplodeFile(maxfileid,file,fname,flenth,fsize,year);
			System.out.println(g.toString());//在控制台输出文件信息

			project.setPropic(g.getAddress());//给project实体的“文件地址”赋值

			return toAjax(projectService.insertProject(project));//将project实体中的值插入数据表中
		}catch (Exception e){
			//return "上传图片失败";
			System.out.println("失败");
			return toAjax(0);
		}

	}


	



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值