Layui 上传图片到磁盘上 + Tomcat 配置虚拟路径

Layui 上传图片到磁盘上 + Tomcat 配置虚拟路径

Tomcat 配置虚拟路径

找到 eclipse 中 tomcat 下面的 server.xml 文件,在 Host 标签里面添加 <Context docBase="E:\upload\image\" path="/upload/image" reloadable="true"/>
其中,docBase 表示的是图片的实际路径, path 表示的是图片的虚拟路径。

1306719-20190218185827428-1778125994.png

1306719-20190218185802708-1382463820.png

1306719-20190219145239788-1074747072.png

在项目根目录下面建立图片的访问路径,即 path 指向的是图片的虚拟路径,如下所示:

1306719-20190217175036288-1283076938.png

图片在磁盘上的实际保存地址如下:

1306719-20190217180359258-1348751684.png

数据库中存放图片的访问路径:

1306719-20190217180609520-1587065081.png

Layui 上传图片到磁盘上

1306719-20190218192511099-1944903593.png
1306719-20190219145206889-2090269135.png
1306719-20190219145333994-1998153548.png

index.jsp 文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${webTitle}</title>
<link href="${pageContext.request.contextPath}/assets/images/suf.ico" rel="shortcut icon">
<link rel="stylesheet" href="${pageContext.request.contextPath}/assets/layui/css/layui.css" media="all">
</head>
<body>
    <h1>大家好,我来复习springmvc了</h1>
    <table class="layui-table">
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>班级</th>
            </tr>
        </thead>
        <c:forEach items="${list}" var="student">
            <tr>
                <td>${student.sno }</td>
                <td>${student.sname }</td>
                <td>${student.age }</td>
                <td>${student.gender }</td>
                <td>${student.grade }</td>
            </tr>
        </c:forEach>
    </table>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>常规使用:普通图片上传</legend>
    </fieldset>
    <div class="layui-upload" style="margin-left: 300px;">
        <button type="button" class="layui-btn" id="upload_image_id">
            <i class="layui-icon">&#xe67c;</i>上传图片
        </button>
        <div class="layui-upload-list">
            <img class="layui-upload-img" src="/${people.imagepath }" style="width: 300px; height: 300px;" id="image_display" />
        </div>
    </div>
    <script src="${pageContext.request.contextPath}/assets/layui/layui.js"></script>
    <script>
        layui.use('upload', function() {
            var $ = layui.jquery;
            var upload = layui.upload;
            //执行实例
            var uploadInst = upload.render({
                elem : '#upload_image_id', //绑定元素
                url : '${pageContext.request.contextPath}/student/imageUpload.do', //上传接口
                accept : 'images', // 图片
                multiple : false,
                exts : 'jpg|png|gif|bmp|jpeg|svg',
                auto : true,
                size : 5 * 1024,// 设置文件最大可允许上传的大小,单位 KB。不支持ie8/9
                method : 'post',
                before : function(obj) {
                    //预读本地文件示例,不支持ie8
                    obj.preview(function(index, file, result) {
                        // console.log(index); //得到文件索引
                        // console.log(file); //得到文件对象
                        // console.log(result); //得到文件base64编码,比如图片
                        $('#image_display').attr('src', result); //图片链接(base64)
                    });
                },
                done : function(res) {
                    //上传完毕回调
                    //如果上传失败
                    if (res.code > 0) {
                        return layer.msg('上传失败!');
                    }
                    //上传成功
                    if (res.code == 0 && res.row > 0) {
                        return layer.msg('上传成功!');
                    }
                },
                error : function() {
                    //请求异常回调
                    return layer.msg('上传出错!');
                }
            });
        });
    </script>
</body>
</html>

1306719-20190218190750242-1572679287.png

1306719-20190218190756427-1028237108.png

StudentInfoSelect.java 文件

package com.libin.springmvc.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.libin.springmvc.entity.People;
import com.libin.springmvc.entity.Student;
import com.libin.springmvc.pub.PubConfig;
import com.libin.springmvc.service.PeopleService;
import com.libin.springmvc.service.StudentService;
import com.libin.springmvc.utils.WebUtil;

@RequestMapping("/student")
@Controller
public class StudentInfoSelect {

    @Resource
    private StudentService studentService;

    @Resource
    private PeopleService peopleService;

    @Autowired
    private PubConfig pubConfig;

    @RequestMapping("/info")
    public String studentInfo(Model model, Student student) {
        List<Student> list = studentService.findAllStudent();
        People peopleName = new People();
        peopleName.setName("Tom");
        People people = peopleService.getPeopleByName(peopleName);
        model.addAttribute("list", list);
        model.addAttribute("people", people);
        return "index";
    }

    @RequestMapping("/imageUpload")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        Map<String, Object> dataMap = new HashMap<>();
        if (!file.isEmpty()) {
            try {
                // String contextPath = PropertiesUtil.getValue("imageUploadPath") + "\\image";
                String contextPath = pubConfig.getImageUploadPath() + "\\image";
                String img = uploadFile(file, contextPath);
                String imgPath = "upload/image/" + img;
                dataMap.put("code", 0);
                dataMap.put("image", imgPath);
                People people = new People();
                people.setName("Tom");
                people.setImagepath(imgPath);
                int row = peopleService.updatePeopleImage(people);
                dataMap.put("row", row);
            } catch (Exception e) {
                dataMap.put("code", 1);
                e.printStackTrace();
            }
        }
        WebUtil.responseOutWithJson(response, dataMap);
    }

    public static String uploadFile(MultipartFile file, String filePath) throws IllegalStateException, IOException {
        Random r = new Random();
        String name = file.getOriginalFilename(); // 文件的真实名称
        String fileName = getShortSystemTime() + r.nextInt(99999999) + "_" + name;
        File tempFile = new File(filePath, fileName);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
        file.transferTo(tempFile);
        return tempFile.getName();
    }

    public static String getShortSystemTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
        return df.format(new Date()).toString();
    }

}

显示界面

完整项目地址:testspringmvc

项目运行界面如下:

1306719-20190217180013870-1168345695.png

访问图片如下:

1306719-20190217180817666-727480628.png

转载于:https://www.cnblogs.com/hglibin/p/10392078.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值