1. 程式人生 > >Bootstrap fileinput v3.0(ssm版)

Bootstrap fileinput v3.0(ssm版)

r.java query err basepath poj ins fse min man

技術分享圖片

說明
在上一個版本即Bootstrap fileinput v2.0(ssm版)的基礎上,增加了多處都需要上傳的需求

技術分享圖片

核心代碼
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 {
//新增文章保存 @Autowired private ArticleService articleService; //用於插入是否成功 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=‘goList‘"+ "},500) </script>"); out.close(); } } //新增文章保存 @RequestMapping("addArticle") public void addArticle(HttpSession session,HttpServletResponse response,Article record,MultipartFile image) throws IllegalStateException, IOException { //如果不傳圖片,那麽則用默認的圖片 if(record.getUrl()==null||record.getUrl().equals("")){ record.setUrl("default.png"); } if(record.getUrl2()==null||record.getUrl2().equals("")){ record.setUrl2("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"; } //uploadFile @ResponseBody @RequestMapping("uploadFile") public Map<String,Object> uploadFile(HttpSession session,MultipartFile myfile) throws IllegalStateException, IOException{ //原始名稱 String oldFileName = myfile.getOriginalFilename(); //獲取上傳文件的原名 //存儲圖片的物理路徑 String file_path = session.getServletContext().getRealPath("WEB-INF/static/upload"); //上傳圖片 if(myfile!=null && oldFileName!=null && oldFileName.length()>0){ //新的圖片名稱 String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf(".")); //新圖片 File newFile = new File(file_path+"/"+newFileName); //將內存中的數據寫入磁盤 myfile.transferTo(newFile); //將新圖片名稱返回到前端 Map<String,Object> map=new HashMap<String,Object>(); map.put("success", "成功啦"); map.put("url",newFileName); return map; }else{ Map<String,Object> map=new HashMap<String,Object>(); map.put("error","圖片不合法"); return map; } } }

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="myfile" data-ref="url" class="col-sm-10 myfile" value=""/>
                                <input type="hidden" name="url" value="">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">封面</label>
                            <div class="col-sm-10">
                                <input type="file" name="myfile" data-ref="url2" class="col-sm-10 myfile" value=""/>
                                <input type="hidden" name="url2" 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({
                uploadUrl:"<%=basePath%>uploadFile",//上傳的地址
                uploadAsync:true, //默認異步上傳
                showUpload: false, //是否顯示上傳按鈕,跟隨文本框的那個
                showRemove : false, //顯示移除按鈕,跟隨文本框的那個
                showCaption: true,//是否顯示標題,就是那個文本框
                showPreview : true, //是否顯示預覽,不寫默認為true
                dropZoneEnabled: false,//是否顯示拖拽區域,默認不寫為true,但是會占用很大區域
                //minImageWidth: 50, //圖片的最小寬度
                //minImageHeight: 50,//圖片的最小高度
                //maxImageWidth: 1000,//圖片的最大寬度
                //maxImageHeight: 1000,//圖片的最大高度
                //maxFileSize: 0,//單位為kb,如果為0表示不限制文件大小
                //minFileCount: 0,
                 maxFileCount: 1, //表示允許同時上傳的最大文件個數
                 enctype: multipart/form-data,
                 validateInitialCount:true,
                 previewFileIcon: "<i class=‘glyphicon glyphicon-king‘></i>",
                 msgFilesTooMany: "選擇上傳的文件數量({n}) 超過允許的最大數值{m}!",
                 allowedFileTypes: [image],//配置允許文件上傳的類型
                 allowedPreviewTypes : [ image ],//配置所有的被預覽文件類型
                 allowedPreviewMimeTypes : [ jpg, png, gif ],//控制被預覽的所有mime類型
                 language : zh
            })
            //異步上傳返回結果處理
            $(.myfile).on(fileerror, function(event, data, msg) {
                console.log("fileerror");
                console.log(data);
            });
            //異步上傳返回結果處理
            $(".myfile").on("fileuploaded", function (event, data, previewId, index) {
                console.log("fileuploaded");
                var ref=$(this).attr("data-ref");
                $("input[name=‘"+ref+"‘]").val(data.response.url);

            });

            //同步上傳錯誤處理
            $(.myfile).on(filebatchuploaderror, function(event, data, msg) {
                console.log("filebatchuploaderror");
                console.log(data);
            });
            
            //同步上傳返回結果處理
            $(".myfile").on("filebatchuploadsuccess", function (event, data, previewId, index) {
                console.log("filebatchuploadsuccess");
                console.log(data);
            });

            //上傳前
            $(.myfile).on(filepreupload, function(event, data, previewId, index) {
                console.log("filepreupload");
            });        
        </script>
    </body>
</html>

數據庫設計

技術分享圖片

源碼地址

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

Bootstrap fileinput v3.0(ssm版)