首页 > 代码库 > Bootstrap fileinput v1.0(ssm版)

Bootstrap fileinput v1.0(ssm版)

前言
bootstrap fileinput是一个很好的文件上传插件。
但是官方不出api,这就尴尬了。
百度一下,每个人写法都不相同,好多代码本身都是错的。我修改后才能跑起来。
综上所述:所以今天我摸索了一天,把今天能够跑的起来的程序核心代码贴上。
完整demo在文章末尾github地址上
基于本人习惯:所用前端控件均为2017年最新的。
最后再唠叨一句:bootstrap不支持IE8极其以下的。没必要与IE较真,毕竟微软人家自己的win10都抛弃ie了。我们又何苦抓着不放呢

 

 

 

功能说明
这个版本的功能比较单一,图片不能提前上传,只能与表单一起提交。也不支持多图上传,适合单张图片上传需求。多张的话,请看我写的另外两篇博客

技术分享

核心代码
因为是ssm项目,所以dao层和pojo是逆向工程生成的,service层和controller层基本一样,所以这3层的代码我就不贴出来,仅仅贴出核心代码的controller和jsp
ArticleController.java

package com.isd.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.isd.pojo.Article;
import com.isd.service.ArticleService;

@Controller
public class ArticleController {
        //用于检测图片是否上传成功
        public void checkUpIsOk(int i,HttpServletResponse response) throws IOException{
            response.setHeader("content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();//获取PrintWriter输出流
            if(i==0){
                out.write("插入失败");
                out.write("<script>setTimeout(function(){"+
                        "history.go(-1);"+ 
                "},500) </script>");
                out.close();
            }else{
                out.write("插入成功");
                out.write("<script>setTimeout(function(){"+
                        "location.href=http://www.mamicode.com/‘goList‘"+ 
                "},500) </script>");
                out.close();
            }
        }
    
       //新增文章保存
        @Autowired
        private ArticleService articleService;
        @RequestMapping("addArticle")
        public void addArticle(HttpSession session,HttpServletResponse response,Article record,MultipartFile image) throws IllegalStateException, IOException {
            //原始名称  
            String oldFilename = image.getOriginalFilename();  
            //上传图片  
            boolean b=image!=null && oldFilename!=null && oldFilename.length()>0;
           //存储图片的物理路径  
            String pic_path = session.getServletContext().getRealPath("WEB-INF/static/upload");
            if(b){
                //新的图片名称  
                String newFileName = UUID.randomUUID() + oldFilename.substring(oldFilename.lastIndexOf("."));  
                //新图片  
                File newFile = new File(pic_path+"/"+newFileName);  
                //将内存中的数据写入磁盘  
                image.transferTo(newFile);    
                //将新图片名称写到book中  
                record.setUrl(newFileName);
                //新增的这条记录插入数据库
                int i=articleService.insert(record);
                checkUpIsOk(i,response);
            }else{
                record.setUrl("default.png");
                int i=articleService.insert(record);
                checkUpIsOk(i,response);
            }
        }
        
        //文章列表跳转
        @RequestMapping("goList")
        public ModelAndView goList(){
            List<Article> artall=articleService.selectAll();
            System.out.println(artall.size());
            ModelAndView mv=new ModelAndView();
            mv.addObject("artall",artall);
            mv.setViewName("list");
            return mv;
        }
        
        //新增文章跳转
        @RequestMapping("goAdd")
        public String goAdd(){
            return "add";
        }
        
    
}

 

add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <meta charset="utf-8">
        <title>图片上传</title>
        <!-- jq -->
        <script type="text/javascript" src="<%=basePath%>static/plugs/jquery-3.1.1.min.js"></script>
        
        <!-- bootstrap -->
        <link rel="stylesheet" href="<%=basePath%>static/plugs/bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" src="<%=basePath%>static/plugs/bootstrap/js/bootstrap.min.js"></script>
        
        <!-- 图片上传即使预览插件 -->
        <link rel="stylesheet" href="<%=basePath%>static/plugs/bootstrap-fileinput/css/fileinput.min.css">
        <script type="text/javascript" src="<%=basePath%>static/plugs/bootstrap-fileinput/js/fileinput.min.js"></script>
        <script type="text/javascript" src="<%=basePath%>static/plugs/bootstrap-fileinput/js/locales/zh.js"></script>
        <style>
            .container{padding-top:60px}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-sm-6 col-sm-offset-3">
                    <form class="form-horizontal"  role="form" method="post"  action="<%=basePath%>addArticle"  enctype="multipart/form-data" >
                        <div class="form-group">
                            <label class="col-sm-2 control-label">描述</label>
                            <div class="col-sm-10">
                                <input type="text" name="describ" class="col-sm-10 form-control"   placeholder="请描述">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">缩略图</label>
                            <div class="col-sm-10">
                                <input type="file" name="image" class="col-sm-10 myfile" value=""/>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-default col-sm-2 col-sm-offset-4">提交</button>
                    </form>
                </div>
            </div>
        </div>
    
        <script>
            $(".myfile").fileinput({
                 showUpload: false, //是否显示上传按钮,跟随文本框的那个
                 showRemove : false, //显示移除按钮,跟随文本框的那个
                 allowedFileTypes: [image],//配置允许文件上传的类型
                 allowedPreviewTypes : [ image ],//配置所有的被预览文件类型
                 allowedPreviewMimeTypes : [ jpg, png, gif ],//控制被预览的所有mime类型
                 language : zh
            })
        </script>
    </body>
</html>

 

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <meta charset="utf-8">
        <title>图片上传</title>
        <!-- jq -->
        <script type="text/javascript" src="${basePath}static/plugs/jquery-3.1.1.min.js"></script>
        
        <!-- bootstrap -->
        <link rel="stylesheet" href="${basePath}static/plugs/bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" src="${basePath}static/plugs/bootstrap/js/bootstrap.min.js"></script>
        
        <!-- 图片上传即使预览插件 -->
        <link rel="stylesheet" href="${basePath}static/plugs/bootstrap-fileinput/css/fileinput.min.css">
        <script type="text/javascript" src="${basePath}static/plugs/bootstrap-fileinput/js/fileinput.min.js"></script>
        <style>
            .container{padding-top:60px}
            .pic{width:100px;}
            td {vertical-align: middle!important;}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
            <button  class="btn btn-default col-sm-2 pull-right add">新增</button>
            <table class="table table-striped table-bordered">
                <caption>文章列表</caption>
            <thead>
                <tr>
                     <th>id</th>
                     <th>描述</th>
                     <th>缩率图</th>
                </tr>
            </thead>
            <tbody>
                <c:forEach var="item" items="${artall}">
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.describ}</td>
                        <td>
                            <img src="${basePath}static/upload/${item.url}" class="pic"/>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>    
            </div>
        </div>
        <script>
            $(".add").click(function(){
                location.href="${basePath}goAdd";
            })
        </script>
    </body>
</html>

 

数据库设计

技术分享

 

 

项目完整地址

https://git.oschina.net/dingshao/bootstrap_fileinput_v1.git

Bootstrap fileinput v1.0(ssm版)