1. 程式人生 > >springMVC 實現圖片上傳

springMVC 實現圖片上傳

1.匯入需要的jar包,或者在maven中引入依賴

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    

2.在springmvc.xml 檔案中配置檔案上傳解析器

<!-- 檔案上傳解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<!-- 上傳檔案最大的大小 -->
    	<property name="maxUploadSize" value="41300260"></property>
    	<!-- 字元編碼 -->
    	<property name="defaultEncoding" value="utf-8"></property>
    </bean>

3.前端的的表單提交型別"multipart/form-data"

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上傳圖片</title>
    <link rel="stylesheet" href="http://www.jq22.com/jquery/bootstrap-3.3.4.css" />
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://www.jq22.com/jquery/bootstrap-3.3.4.js"></script>
</head>
<body>

   <div style="width: 600px;height: auto;background-color: aliceblue;margin: 5% auto auto auto;">
    <form  action="uploadBook" method="post" enctype="multipart/form-data" >
        <div class="col-sm-offset-4 col-sm-10">
            <h2>書籍資訊錄入</h2>
        </div>
        <div class="form-group" >
            <label >書名</label>
            <input type="text" class="form-control info" name="sname" id="sname" onfocus="showTips('sname','請輸入書名')"
                   onblur="checkFormat('sname','書名不能為空')"><span id="snamespan"></span>
        </div>
        <div class="form-group">
            <label >價格</label>
            <input type="number" class="form-control" name="sprice" placeholder="請輸入價格" >
        </div>
        <div class="form-group">
            <label >所屬型別</label>
            <select class="form-control" id="type" name="type">
                <option value="">請選擇</option>
                <option value="1">計算機</option>
                <option value="2">經濟管理</option>
                <option value="3">勵志言情</option>
                <option value="4">育兒家教</option>
                <option value="5">繪畫攝影</option>
                <option value="0">其他</option>
            </select>
        </div>
        <div class="form-group">
            <label >圖片</label>
            <input type="file" id="bimg" name="bimg">
        </div>
        <div class="col-sm-offset-4 col-sm-10">
            <button type="submit" class="btn btn-default">新增書籍</button>
        </div>
    </form>
    </div>
</body>
<script>
    /*聚焦時對input內容格式進行提示*/
    function showTips(id,info){
        document.getElementById(id+"span").innerHTML="<font color='#444359'>"+info+"</font>";
    }
    /*離焦時input內容進行檢測*/
    function checkFormat(id,info){
        var novals = document.getElementById(id).value;
        if(novals ==""){
            document.getElementById(id+"span").innerHTML="<font color='red'>"+info+"</font>";
        }else{
            document.getElementById(id+"span").innerHTML="";
        }
    }
</script>
</html>

實際頁面如下:
在這裡插入圖片描述
4.獲取表單裡的資料,注意檔案的型別是MultipartFile ,普通表達引數的型別是MultipartHttpServletRequest ,獲取表單值的方法是value=getParameter(key);

@ResponseBody
    @RequestMapping(value = "uploadBook",method = RequestMethod.POST)
    public ReturnData addBookInfo(@RequestParam("bimg")MultipartFile file, MultipartHttpServletRequest request) throws IOException {
        if(file != null){
            String path=null;// 檔案路徑
            String type = null;//檔案型別
            String fileName=file.getOriginalFilename();// 檔案原名
            logger.info("上傳的原始檔名稱:"+fileName);
            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if(type != null){
                if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){
                    // 專案在容器中實際釋出執行的根路徑
                    String realPath=request.getSession().getServletContext().getRealPath("/");
                    // 自定義的檔名稱
                    String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
                    // 設定存放圖片檔案的路徑
                    path=realPath+"upload/"+trueFileName;
                    logger.info("圖片儲存的路徑是:"+path);
                    // 轉存檔案到指定的路徑
                    file.transferTo(new File(path));
                    String title=request.getParameter("sname");
                    String bsprice=request.getParameter("sprice");
                    String btype=request.getParameter("type");
                    Books book = new Books();
                    book.setBimg(trueFileName);
                    book.setType(btype);
                    book.setBprice(bsprice);
                    book.setBname(title);
                     int rows =userService.addBook(book);
                     if(rows>0){
                         logger.info("資料填進資料庫");
                     }
                }else {
                    return ReturnData.error(1,"檔案型別錯誤");
                }
            }else{
                return ReturnData.error(2,"檔案型別為空");
            }
        }else{
            return ReturnData.error(3,"沒有找到相對應的檔案");
        }
        return ReturnData.ok("書籍資訊新增成功");
    }

5.總結,在獲取普通表單引數的時候,使用HttpServletRequest的getAttribute(key)方法,拿不到普通引數的值,後來在更換為MultipartHttpServletRequest,在除錯的時候,發現multipartParametet,就試著用getParameter(key)獲取普通引數值.
在這裡插入圖片描述
在這裡插入圖片描述

在這裡插入圖片描述
在這裡插入圖片描述