tomcat配置虚拟路径映射磁盘文件列表图片回显和放大功能实现springboot项目的文件虚拟路径映射

news2024/10/7 20:29:58

tomcat映射磁盘图片

  • 1.以E盘为例,在E盘创建目录testReceive
  • 2.配置tomcat虚拟路径映射e盘本地文件
  • 3.代码层面创建上传文件(此处为图片)工具类
      • 3.1(校验图片格式、获取当前主机ip、上传图片至本机目的地,获取上传图片地址)
  • 4.调用上传图片工具类接口serviceImp实现
      • 4.1后台接口
      • 4.2实现接口类
      • 4.3mapper文件接口和sql语句
      • 4.4 插入数据库图片上传的链接地址
  • 5.前台上传form表单
      • 5.1 form表单
      • 5.2 表单函数
  • 6.数据回显
    • 6.1数据列表展示
    • 6.2列表formatter每行函数
  • 7.图片上传本地和列表回显和放大
  • 8.其实用springboot两行代码就实现这个功能了
  • 9.上传图片的命名和路径

1.以E盘为例,在E盘创建目录testReceive

在这里插入图片描述

2.配置tomcat虚拟路径映射e盘本地文件

找到tomcat服务器的conf目录下的server.xml文件,找到最下方左右位置

<Context docBase="E:\testReceive" path="/testReceive" reloadable="false"/>		

在这里插入图片描述

3.代码层面创建上传文件(此处为图片)工具类

3.1(校验图片格式、获取当前主机ip、上传图片至本机目的地,获取上传图片地址)

import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

public class UploadUtil {
    /**
     * @description 检查是否是 bmp/gif/jpg/png图片
     * @param fileList
     * @return java.lang.Boolean
     */
    public static Boolean checkImg(List<MultipartFile> fileList){
        if(fileList.isEmpty()){
            return false;
        }else {
            for (MultipartFile file:fileList) {
                try {
                    //通过ImageIO检查是否是 bmp/gif/jpg/png图片,是则有东西返回(具体是啥,我也不清楚)
                    Image image = ImageIO.read(file.getInputStream());
                    return image!=null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return false;
        }
    }

    /**
     * @description 图片上传
     * @param fileList
     * @param request
     * @return java.lang.String
     */
    public static List<String> upload(List<MultipartFile> fileList, HttpServletRequest request, String dirPath){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");        
        String formatDate =simpleDateFormat.format(new Date(System.currentTimeMillis()));
        List<String> fileUploadList = new ArrayList<>();
        //获取当前主机ip
        String ip =UploadUtil.getRealIpv4();
        if (ip.indexOf("failUpload=>>>")>0){
            fileUploadList.add(ip);
            return fileUploadList;
        }
        for (MultipartFile file: fileList) {
            String fileName = file.getOriginalFilename();
            //将图片文件名进行重命名
            fileName = System.currentTimeMillis()+""+UUID.randomUUID() + fileName;
            //创建文件目录
            File dest = new File(new File(dirPath).getAbsolutePath()+"/"+formatDate+"/"+fileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            try {
            //将上传的图片写入本地创建的目录内部
                file.transferTo(dest);  
                //获取当前图片上传的目录和目录图片位置 
			 //地址格式如--》 /testReceive/当前年和月/时分秒的数字化+uuid.(jpg/png/gif)  
			                                       					    
            	fileUploadList.add("/"+dirPath.substring(dirPath.indexOf("E:\\")+3)+"/"+formatDate+"/"+fileName);
            } catch (IOException e) {
                e.printStackTrace();
                fileUploadList.add("failUpload=>>>上传失败异常:"+e.toString());
            }
        }
        return  fileUploadList;
    }

    /**
     * @description 删除文件
     * @return Boolean
     */
    public static Boolean deleteFile(String dirPath,String url){
        //截取第四个“/”后面的字符串
        int i1=url.indexOf('/');
        int i2=url.indexOf('/',i1+1);
        int i3=url.indexOf('/',i2+1);
        int i4=url.indexOf("/",i3+1);
        String substring=url.substring(i4+1,url.length());
        String relPath=dirPath+substring;
        Boolean flag = false;
        File file = new File(relPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

//获取当前计算机IPv4地址
    public static String getRealIpv4() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                // 去除回环接口,子接口,未运行和接口
                if (netInterface.isLoopback() || netInterface.isVirtual()
                        || !netInterface.isUp()) {
                    continue;
                }
                if (!netInterface.getDisplayName().contains("Intel")
                        && !netInterface.getDisplayName().contains("Realtek")) {
                    continue;
                }
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip != null) {
                        // 描述为 Realtek PCIe GbE Family Controller的ipv4
                        if (ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
                break;
            }
        } catch (SocketException e) {
            System.err.println("failUpload=>>>Error when getting host ip address"
                    + e.getMessage());
           return new String ("failUpload=>>>Error when getting host ip address"+e.getMessage());
        }
        return new String("failUpload=>>>getting host ip address IS NULL");
    }
}

4.调用上传图片工具类接口serviceImp实现

4.1后台接口

    @Controller
	@RequestMapping("/xxxControl")
    @RequestMapping("/insertUploadPhotoUrl.do")
    @ResponseBody
    String insertUploadPhotoUrl(HttpSession session, HttpServletRequest request,@RequestParam(value = "photoList", required = false) List<MultipartFile> photoList) {
        return xxxService.insertUploadPhotoUrl(session, request,photoList);
    }

4.2实现接口类

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;
..............

 public String insertUploadPhotoUrl(HttpSession session, HttpServletRequest request,List<MultipartFile> photoList) {
  JSONObject jObject = new JSONObject();
 xxxClass     xxxentity =new xxxClass(); 
 xxxentity.setUserName(request.getParameter("username"));
  xxxentity.setRemark(request.getParameter("remark"));
  try {
            if (!photoList.get(0).getOriginalFilename().isEmpty() && photoList.size() > 0 && photoList.size() < 4) {
            //图片将要保存e盘创建的位置
            String desktopDir ="E:\\testReceive";
            //校验上传的是否是图片格式
            Boolean img =UploadUtil.checkImg(photoList);
            if (img){//true的情况下
            //获取已经写入至本地目录的图片地址
                List<String> fileUploadList =UploadUtil.upload(photoList,request,desktopDir);
                //检验是否失败
                if (fileUploadList.toString().indexOf("failUpload=>>>")>0){
                    jObject.put("message", stringBuffer.append(fileUploadList.toString()));
                }else{
                //未失败的情况下依次获取上传的本地磁盘    链接字符串
                    if (fileUploadList.size() > 0 && fileUploadList.size() < 4) {
                        for (int i = 0; i < fileUploadList.size(); i++) {
                            if (i == 0) {
                                xxxentity .setPhoto1(fileUploadList.get(i));
                            } else if (i == 1) {
                                xxxentity .setPhoto2(fileUploadList.get(i));
                            } else if (i == 2) {
                                xxxentity .setPhoto3(fileUploadList.get(i));
                            }
                        }
                    }else{
                        jObject.put("message", "插入异常:"+stringBuffer.append("插入图片超过3张"));
                    }
                }
            }else {
                jObject.put("message", "图片后缀格式名不正确,请上传bmp/gif/jpg/png格式的图片;");
                return jObject.toString();
            }
        }
        } catch (Exception e) {
            jObject.put("message", "插入异常:"+stringBuffer.append(e.toString()));
            e.printStackTrace();
        }
        //插入数据数据库 表中至少创建三个字段 photo1、photo2、photo3
	int  count = xxxMapper.insertUploadPhotoUrl(xxxentity);
}

4.3mapper文件接口和sql语句

	Integer insertUploadPhotoUrl(xxxClass xxxentity);
		
	<insert id="insertUploadPhotoUrl">
        insert into xxxtable_name(user_name,remark,photo1,photo2,photo3,create_time)
         values
         (   
         #{userName}, //这些都是 xxxClass对象的属性实例的值     
        #{remark},   
        #{photo1},
        #{photo2},
        #{photo3}),
		now()
		)
    </insert>
	

4.4 插入数据库图片上传的链接地址

字段photo1获得当前地址
/testReceive/2023-04/1681284642429a15d1c35-27bf-4391-a57e-d7612f4cfdadmount1.jpg
字段photo2获得当前地址
/testReceive/2023-04/1681284642430a15d1c35-27bf-4391-a57e-d7612f4cfdadmount2.jpg
字段photo3获得当前地址
/testReceive/2023-04/1681284642435a15d1c35-27bf-4391-a57e-d7612f4cfdadmount3.jpg

5.前台上传form表单

5.1 form表单

<div id="xxxwindowAdd" class="easyui-window"  closed="true" title="xxx记录添加" style="width:634px;height:700px;padding:10px;">
				<div  style="width:600px;padding:30px 125px">
					<form id="xxxFormAdd" class="easyui-form" enctype="multipart/form-data" method="post" data-options="novalidate:true" >
						<div style="margin-bottom:20px">
							<tr>
								<td>姓名:</td>
								<td><input class="easyui-textbox" style="width:100%;height:32px" type="text" name="userName"
							 data-options="required:false,prompt:'输入名字'"></input></td>
							</tr>
						</div>
					
						<div style="margin-bottom:20px">
							<tr>
								<td>备注:</td>
								<td><input class="easyui-textbox" style="width:100%;height:60px" name="remark" data-options="multiline:true,prompt:'备注选填'" ></input></td>
							</tr>
						</div>
						<div style="margin-bottom:20px">
							<tr>
								<td>图片上传:</td>
								<td><input class="easyui-filebox" style="width: 100%;height: 32px" name="photoList" value="no"
										   data-options="multiple:true,prompt:'最多添加3张图片',buttonText: '添加图片'"></input></td>
							</tr>
						</div>
						<div>
							<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="submitForm()" style="width:100%;height:32px">数据提交</a>
						</div>
				</form>

				</div>
				<div style="text-align:center;padding:39px;width: 600px">
					<a href="javascript:void(0)" class="easyui-linkbutton" style="margin-right: 100px;width: 75px" onclick="$('#xxxFormAdd').form('clear');">清空</a>
					<a href="javascript:void(0)" class="easyui-linkbutton"  style="margin-left: 100px;width: 75px" onclick="autoLoadDate()">自动加载数据</a>
				</div>
			</div>

5.2 表单函数

function submitForm(){
    $('#xxxFormAdd').form('submit',{
        url:ProjectPath + "/xxxControl/insertUploadPhotoUrl.do",
        onSubmit:function(){
            var isValid = $(this).form('validate');
            if (!isValid){
                $.messager.alert("空内容","必填项内容为空", "error");
                return false
            }
        },
        success:function (res) {
            res=JSON.parse(res)
            if (res.result=='success'){
                $('#xxxFormAdd').form('clear');
                $('#xxxwindowAdd').window('close'); // close a window
       			......
 				......
            }else {
                $.messager.alert("新增失败",res.message, "error");
            }
        }
    });
}


function autoLoadDate(){
    debugger 
   $('#xxxFormAdd').form('load',{
		userName:'你想写的内容',
 });
}

6.数据回显

6.1数据列表展示

# 列表
<table id="returnToDepotReport" class="easyui-datagrid" style="width:100%;height: 100%"
				   data-options="
					   	fit:true,
 						rownumbers:true,
						singleSelect:true,
						pagination:true,
						pageList:[50,100,200,400,1000],
						pageNumber:1,
						pageSize:50,
						striped:true,
						autoRowHeight:false,
						idField:'id',
						fitColumns:true,
					   toolbar:'#returnToDepotToolBar'
						">
				<thead>
				<tr>
					<th data-options="field:'id',align:'center',width:10,hidden:true">主键id</th>
					<th data-options="field:'userName',align:'center',width:220">姓名</th>
					<th data-options="field:'photo1',width:80,height:80,align:'center',formatter:formatterPhoto" th:text="无" >图片1</th>
					<th data-options="field:'photo2',width:80,height:80,align:'center',formatter:formatterPhoto" th:text="无" >图片2</th>
					<th data-options="field:'photo3',width:80,height:80,align:'center',formatter:formatterPhoto" th:text="无" >图片3</th>
					<th data-options="field:'remark',align:'center',width:150">备注</th>					
					<th data-options="field:'create_time',align:'center',width:150">创建时间</th>
				</tr>
				</thead>
			</table>
# 预览图片
<div class="easyui-window"  closed="true" id="show_anzhuang_pic" style="width:800px;height:675px;" title="预览图片">
				<img alt="" src="" id="img_show_anzhuang_pic" style="width:800px;">
			</div>

6.2列表formatter每行函数

function formatterPhoto(val) {
		if (val != undefined) {
			return '<img src="' +val + '"  style="width:100px;height:100px;" onclick="showBigPhoto(\'' + val + '\')">';
		}else{
			return '<img src="' +'' + '"   style="width:100px;height:100px;" onclick="showBigPhoto(undefined)">';
		}
	}

	function showBigPhoto(url){
		debugger
		if (url==undefined){
			$.messager.alert("空图片", "此处未上传图片", "error");
		}else{
			$('#show_anzhuang_pic').window('open');
			$('#img_show_anzhuang_pic').attr("src",url);
		}
	}
	

7.图片上传本地和列表回显和放大

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

8.其实用springboot两行代码就实现这个功能了


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

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    /*
     * 在配置文件中配置的文件保存路径
     */
    private String mapPath="file:/E:/testReceive/";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/testReceive/**").addResourceLocations(mapPath);
        // TODO Auto-generated method stub
        super.addResourceHandlers(registry);
    }

}

9.上传图片的命名和路径

Tomcat配置本地文件映射

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/415863.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

javaWeb(HTTP、Tomcat、Servlet)

目录 HTTP Web 服务器 - Tomcat 简介 基本使用&#xff1a;下载、安装、卸载、启动、关闭、配置、部署项目 IDEA中创建 Maven Web项目​编辑 IDEA中使用 Tomcat Servlet 快速入门 Servlet 执行流程 Servlet 生命周期 Servlet 体系结构 Servlet urlPattern配置 XM…

【从零开始学Skynet】实战篇《球球大作战》(五):gateway代码设计(中)

1、编码和解码 我们来实现两个辅助方法str_unpack和str_pack&#xff0c;用于消息的解码和编码。 &#xff08;1&#xff09;str_unpack代码 local str_unpack function(msgstr)local msg {}while true dolocal arg, rest string.match( msgstr, "(.-),(.*)")if…

【web自动化测试】

文章目录web自动化测试第一章 web自动化入门1.什么是自动化&#xff1f;1.1 优点2.什么是自动化测试&#xff1f;2.1 自动化测试能解决什么问题&#xff1f;2.2 自动化相关知识2.2.1优点2.2.2 误区2.3 自动化测试分类3.什么是Web自动化测试&#xff1f;3.1 什么Web项目适合做自…

Flutter 了解 Element

一 Element 概念 这个玩意的概念。到底是什么 &#xff1f; 官方解释是在树中特定位置的实例。 二 继承关系 element 有 ComponentElement 和 RenderObjectElement 之分 1 ComponentElement class StatelessElement extends ComponentElement class StatefulElement extend…

计及调度经济性的光热电站储热容量配置方法

目录 1 主要内容 目标函数 光热电站能量传递过程 2 部分程序 3 程序结果 4 程序链接 1 主要内容 该程序复现《计及调度经济性的光热电站储热容量配置方法》模型&#xff0c;综合考虑火电机组发电成本、光热发电并网消纳的环境效益和运行维护成本、系统旋转备用成本等调度…

rk3568点亮LCD(RGB)

rk3568 Android11/12 调试 RGB 屏 RGB一般是指RGB色彩模型(RGB color model)&#xff0c;是工业界的一种颜色标准。RGB接口占用的资源较多&#xff0c;所以这个接口的LCD刷新率非常快&#xff0c;软件控制也比较简单。缺点是控制需要增加电路&#xff0c;软件初始化需要增加程…

【BOM浏览器对象模型】

BOM浏览器对象模型1 本节目标2 BOM概述3 window对象的常见事件3.1 窗口加载事件3.2 调整窗口大小事件4 定时器4.1 两种定时器4.2 setTimeout()定时器4.3 停止setTimeout()定时器4.4 setInterval()定时器4.5 停止setInterval()定时器4.6 this指向问题5 JS执行队列5.1 JS是单线程…

BUUCTF-.htaccess-sql.fuzz-D盾

第七周第一次 目录 WEB [MRCTF2020]你传你&#x1f40e;呢 ​编辑 [极客大挑战 2019]HardSQL Crypto 萌萌哒的八戒 传统知识古典密码 Misc 假如给我三天光明 后门查杀 WEB [MRCTF2020]你传你&#x1f40e;呢 文件上传 我们进行尝试 设置一个 1.jpg的一句话木马 G…

RabbitMQ之高级特性

文章目录一、消息确认机制&#x1f389;1.1 消息发送确认(生产者)&#x1f539;confirm 确认模式&#x1f539;return 回退模式&#x1f6a9;1.2 消息接收确认(消费者)&#x1f538;none 自动确认&#x1f538;auto 异常确认&#x1f538;manual 手动确认二、消费端限流 (prefe…

创略科技联合创始人兼总裁杨辰韵:AIGC、隐私计算赋能数字营销的本质是“以客户为中心”丨数据猿专访...

‍数据智能产业创新服务媒体——聚焦数智 改变商业MarTech概念现身已超十年&#xff0c;伴随着企业数字化转型的大背景&#xff0c;中国MarTech市场也迎来了高速发展。据《2022年中国MarTech市场洞察报告》数据显示&#xff0c;2017-2021年&#xff0c;中国 MarTech产业规模从…

H264码流中 SPS PPS SEI 详解

1 客户端抓包 在做客户端视频解码时&#xff0c;一般都会使用Wireshark抓包工具对接收的H264码流进行分析&#xff0c;如下所示&#xff1a; 在这里我们可以看到对解码视频起关键作用的SPS和PPS。 2、双击SPS内容如下&#xff1a; 那么从上面的sps中我们知道图像的宽&#x…

【从零开始学Skynet】实战篇《球球大作战》(二):结构设计

万丈高楼平地起&#xff0c;既然这是个“大项目”&#xff0c;就要有大项目的样子&#xff0c;就要有所规划&#xff0c;下面先把项目的目录结构搭起来。 1、目录结构 建议把Skynet框架放到一个文件夹里&#xff0c;把所有自己编写的内容都放到外层的文件夹里。建立如下表所示的…

MySQL运维10-MySQL数据的导入导出

文章目录0、概述1、mysqldump导出数据mysql导入数据1.1、使用mysqldump导出数据1.1.1、使用--tables导出指定表1.1.2、使用--tab选项将表定义文件和数据文件分开导出1.1.3、使用--fields-terminated-by选项定义数据分隔符1.1.4、使用--databases选项导出整个库或多个库1.1.5、使…

Python算法设计 - 蒙特卡洛法

版权声明&#xff1a;原创不易&#xff0c;本文禁止抄袭、转载&#xff0c;侵权必究&#xff01; 目录一、蒙特卡洛法二、求圆周率π三、Python算法实现四、作者Info一、蒙特卡洛法 蒙特卡洛方法又称统计模拟法&#xff0c;随机抽样技术&#xff0c;是一种随机模拟方法&#x…

pytorch进阶学习(五):神经网络迁移学习应用的保姆级详细介绍,如何将训练好的模型替换成自己所需模型

代码资源和数据集资源使用进阶学习&#xff08;四&#xff09;中的代码&#xff0c;大家可以配合食用哟~ pytorch进阶学习&#xff08;四&#xff09;&#xff1a;使用不同分类模型进行数据训练&#xff08;alexnet、resnet、vgg等&#xff09;_好喜欢吃红柚子的博客-CSDN博客…

数据结构之八大排序算法

文章目录一.常见的排序二.插入排序三.希尔排序四.选择排序五.堆排序六.冒泡排序七.快速排序八.归并排序九.计数排序十.排序总结一.常见的排序 排序&#xff1a;所谓排序&#xff0c;就是使一串记录&#xff0c;按照其中的某个或某些关键字的大小&#xff0c;递增或递减的排列起…

pytorch性能分析工具Profiler

1. Torch Profiler工具介绍 https://zhuanlan.zhihu.com/p/360479566 PyTorch Profiler 是一个开源工具,可以对大规模深度学习模型进行准确高效的性能分析。包括如下等功能: 分析model的GPU、CPU的使用率各种算子op的时间消耗trace网络在pipeline的CPU和GPU的使用情况Profil…

Educational Codeforces Round 146 (Rated for Div. 2) - B. Long Legs(思维 数学)

题目如下&#xff1a; 题目链接 题解 or 思路&#xff1a; 我们可以发现我们有两个可选的入手方向&#xff1a; 1.正推 2.反推 我们可以发现正推似乎看不出来什么东西&#xff0c;而反推可以发现一个性质&#xff01; 性质如下&#xff1a; 我们假设最终的腿长为 MMM 可以得到…

sql需要注意的地方 以及 云记模块逻辑

标题模糊搜素时 sql语句需要注意的地方 用concat拼; 用户行为 actionName 进入发布云记页面 actionNameview 添加或修改云记 actionNameaddOrUpdate 查询云记详情 actionNamedetail 删除云记 actionNamedelete 分页查询云记列表 …

第05章_数组

第05章_数组 讲师&#xff1a;尚硅谷-宋红康&#xff08;江湖人称&#xff1a;康师傅&#xff09; 官网&#xff1a;http://www.atguigu.com 本章专题与脉络 1. 数组的概述 1.1 为什么需要数组 需求分析1&#xff1a; 需要统计某公司50个员工的工资情况&#xff0c;例如计…