1. 程式人生 > >Layui 上傳圖片到磁盤上 + Tomcat 配置虛擬路徑

Layui 上傳圖片到磁盤上 + Tomcat 配置虛擬路徑

失敗 servlet color on() vat amp 異常 lang prev

Layui 上傳圖片到磁盤上 + Tomcat 配置虛擬路徑

Tomcat 配置虛擬路徑

找到 eclipse 中 tomcat 下面的 server.xml 文件,在 Host 標簽裏面添加 <Context docBase="E:\upload\image\" path="/upload/image" reloadable="true"/>
其中,docBase 表示的是圖片的實際路徑, path 表示的是圖片的虛擬路徑。

技術分享圖片

技術分享圖片

技術分享圖片

在項目根目錄下面建立圖片的訪問路徑,即 path 指向的是圖片的虛擬路徑,如下所示:

技術分享圖片

圖片在磁盤上的實際保存地址如下:

技術分享圖片

數據庫中存放圖片的訪問路徑:

技術分享圖片

Layui 上傳圖片到磁盤上

技術分享圖片

技術分享圖片

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>springmvc測試頁面</title>
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/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}/plugins/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 : '/student/imageUpload.do', //上傳接口
                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>

技術分享圖片

技術分享圖片

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.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.service.PeopleService;
import com.libin.springmvc.service.StudentService;
import com.libin.springmvc.utils.PropertiesUtil;
import com.libin.springmvc.utils.WebUtil;

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

    @Resource
    private StudentService studentService;

    @Resource
    private PeopleService peopleService;

    @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("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().mkdir();
        }
        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

項目運行界面如下:

技術分享圖片

訪問圖片如下:

技術分享圖片

Layui 上傳圖片到磁盤上 + Tomcat 配置虛擬路徑