springmvc+mybatis 處理圖片(一):上傳圖片


一直覺得上傳圖片文件之類的很難,所以最后才處理圖片,發現也並沒有那么難,開始正文。

思路:將前台上傳的file存到MutipartFile類型字段中,再將MulipartFile轉換為pojo類中的byte[ ]數組,最后存入數據庫longBlob類型字段中
1. 數據庫設計,將圖片newsPic字段類型設置為longblob或blob

2. 准備jar包:commons-fileupload和commons-io,我用的是commons-fileupload-1.3.1.jar和commons-io-2.4.jar,也可以在這里下載。 
3. 在springmvc-config.xml中進行上傳文件的配置

<!-- 對上傳文件的配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding">
        <value>UTF-8</value>
    </property>
    <property name="maxUploadSize">
        <value>32505856</value><!-- 上傳文件大小限制為31M,31*1024*1024 -->
    </property>
    <property name="maxInMemorySize">
        <value>4096</value>
    </property>
</bean>

form表單里面有文件上傳時,必須要指定enctype屬性值為multipart/form-data,意思是以二進制流的形式傳輸文件。否則會報錯上傳不了。
而因為在form表單中增加了:enctype="multipart/form-data"這個屬性,會將數據轉換為二進制,導致接收到的值都為空值,因此要在spring的配置文件中配置multipartResolver
4. addNews.jsp

<form action="addNewst" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>
                <input type="file" size="50" name="newsPicture"/>
            </td>
        </tr>
        <!--省略其他字段的代碼-->
    </table>
</form>

5. NewsMapper.java和NewsDynaSqlProvider.java
(1) NewsMapper.java

//動態插入新聞
@SelectProvider(type=NewsDynaSqlProvider.class,method="insertNews")
void save(News news);

(2) NewsDynaSqlProvider.java

//動態插入
public String insertNews(final News news){
    return new SQL(){
        {
            INSERT_INTO("news");
            if(news.getNewsTitle() != null && !news.getNewsTitle().equals("")){
                VALUES("newsTitle", "#{newsTitle}");
            }
            if(news.getNewsAbstract() != null && !news.getNewsAbstract().equals("")){
                VALUES("newsAbstract", "#{newsAbstract}");
            }
            if(news.getNewsAuthor() != null && !news.getNewsAuthor().equals("")){
                VALUES("newsAuthor", "#{newsAuthor}");
            }
            if(news.getNewsTime() != null && !news.getNewsTime().equals("")){
                VALUES("newsTime", "#{newsTime}");
            }
            if(news.getNewsContent() != null && !news.getNewsContent().equals("")){
                VALUES("newsContent", "#{newsContent}");
            }
            if(news.getNewsPic() != null && !news.getNewsPic().equals("")){
                VALUES("newsPic", "#{newsPic,jdbcType=BLOB}");
            }
        }
    }.toString();
}

6. TestService.java和TestServiceImpl.java
(1) TestService.java

/**
* 添加新聞
* @param News 新聞對象
* @MultipartFile newsPic 新聞圖片
* @throws Exception 
*/
void addNewsAndPic(News news, MultipartFile newsPic) throws Exception;

(2) TestServiceImpl.java

@Override
public void addNewsAndPic(News news, MultipartFile newsPic) throws Exception {
    byte[] b1 = newsPic.getBytes(); news.setNewsPic(b1);
    newsMapper.save(news);
}

7. NewsController.java

/**
 * 處理添加請求
 * @param String flag 標記, 1表示跳轉到添加頁面,2表示執行添加操作
 * @param News news  要添加的新聞對象
 * @param ModelAndView mv
 * @throws Exception 
 * */
@RequestMapping(value="/addNewst")
 public ModelAndView addNewst(String flag, @ModelAttribute News news, MultipartFile newsPicture, ModelAndView mv, HttpSession session) throws Exception{
     if(flag.equals("1")){
         mv.setViewName("addNews");
     }else{
         testService.addNewsAndPic(news, newsPicture);
         mv.setViewName("redirect:/htNews");
     }
     return mv;
 }

SpringMVC中從前台到后台通過表單傳遞數據:

(1) 表單的name屬性值必須和接受的參數同名。否則,接收到的參數為null
(2) 表單的name屬性值必須和接收對象的屬性同名。否則,接收到的參數為null

8. News.java

public class News implements Serializable{
    private Integer newsID;
    private String newsTitle;
    private String newsAbstract;
    private String newsAuthor;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date newsTime;
    private String newsContent;
    private byte[] newsPic;//新聞照片
    
    public News(){
        super();
    }
    //setter and getter
}

參考:https://blog.csdn.net/j277699931/article/details/50413864
二、.jsp改進,讀取input:file的路徑后,顯示本地圖片

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>title</title>
<style type="text/css">
#imagePreview {   
width: 160px;   
height: 120px;   
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);   
}   
</style>
</head>
<body>
<form action="addNewst" id="newsForm" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>
                <div id="imagePreview"></div>
                <input id="imageInput" type="file" size="50" name="newsPicture" onchange="loadImageFile()"/>
            </td>
        </tr>
        <!--省略其他代碼-->
    </table>
</form>
<script type="text/javascript">
var loadImageFile = (function () {   
    if (window.FileReader) {   
    var oPreviewImg = null, oFReader = new window.FileReader(),   
    rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;   
      
      
    oFReader.onload = function (oFREvent) {   
    if (!oPreviewImg) {   
    var newPreview = document.getElementById("imagePreview");   
    oPreviewImg = new Image();   
    oPreviewImg.style.width = (newPreview.offsetWidth).toString() + "px";   
    oPreviewImg.style.height = (newPreview.offsetHeight).toString() + "px";   
    newPreview.appendChild(oPreviewImg);   
    }   
    oPreviewImg.src = oFREvent.target.result;   
    };   
      
      
    return function () {   
    var aFiles = document.getElementById("imageInput").files;   
    if (aFiles.length === 0) { return; }   
    if (!rFilter.test(aFiles[0].type)) { alert("You must select a valid image file!"); return; }   
    oFReader.readAsDataURL(aFiles[0]);   
    }   
      
      
    }   
    if (navigator.appName === "Microsoft Internet Explorer") {   
    return function () {   
    alert(document.getElementById("imageInput").value);   
    document.getElementById("imagePreview").filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = document.getElementById("imageInput").value;   
      
      
    }   
    }   
    })();   
</script>
</body>
</html>

效果如圖:

參考:https://blog.csdn.net/dracotianlong/article/details/38046939

------------------------------------------------------分界線------------------------------------------------------------
遇到的錯誤:
1. SpringMVC表單提交后,Controller接收到的值都是null,如圖


報錯如下:

四月 13, 2018 10:43:33 上午 org.apache.catalina.core.StandardWrapperValve invoke
嚴重: Servlet.service() for servlet [springmvc] in context with path [/SpringDemo] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.game.controller.NewsController.addNewst(NewsController.java:58)

原因:沒有配置multipartResolver,參考:https://blog.csdn.net/MODjie/article/details/79076455

2. 點擊”新聞管理“的界面,就在顯示圖片的controller中報空指針異常java.lang.NullPointerException,但是頁面的所有功能都能正常使用,開始始終不明白怎么回事,后來發現是因為有的新聞沒有添加圖片,造成在加載頁面獲取新聞的二進制文件流時報空指針異常。

java.lang.NullPointerException
    at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)
    at com.game.controller.NewsController.newsPic(NewsController.java:105)

如圖:

------------------------------------------------------分界線------------------------------------------------------------

Mysql中的BLOB數據類型
在計算機中,BLOB是數據庫中經常用來存儲二進制文件的字段類型,典型的BLOB是一張圖片或一個聲音文件。
MySQL中,BLOB是個類型系列,包括:TinyBlob、Blob、MediumBlob、LongBlob,這幾個類型之間的唯一區別是存儲文件的最大大小的不同。

類型 大小(單位:字節)
TinyBlob 最大 255
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM