1. 程式人生 > >ssm框架實現圖片上傳並顯示(myeclips)

ssm框架實現圖片上傳並顯示(myeclips)

ssm框架實現圖片上傳並顯示

第一步:匯入common-io以及common-fileupload兩個jar包,儘量新一點,老的有可能出錯

第二步:配置圖片上傳儲存的位置,針對myeclips來說,開啟檔案D:\Java\MyEclipse.metadata.me_tcat\conf\server.xml
在之間新增<Context docBase="D:\File" path="/images" reloadable="false"/>
其中D:\File是我們儲存到本地的路徑,/images是我們使用的虛擬路徑,用過/images的路徑可以得到D:\File路徑下的圖片

第三步:建立實體類,例子給出圖書的實體類,資料表(books)如圖
這裡寫圖片描述
程式碼如下:(注意多添加了MultipartFile屬性)

public class Books {
    private Integer id;
    private String bookname;
    private Double price;
    private Integer stock;
    private String img;
     private MultipartFile file;
    public Integer getId() {
        return id;
    }
    public
MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } public void setId(Integer id) { this.id = id; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this
.bookname = bookname; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } }

第四步:給出Dao層,Service層,ServiceImpl層,程式碼如下:

public interface AdBookDao {
    public void addBook(Books book);
}
public interface AdBookService {
    public void addBookService(Books book);
}

@Service
public class AdBookServiceImpl implements AdBookService{

    @Autowired
    private AdBookDao bookDao;

    public void addBookService(Books book) {
        // TODO Auto-generated method stub
        bookDao.addBook(book);
    }

}

第五步:編寫controller層

package com.qut.controller;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qut.pojo.Books;
import com.qut.service.impl.AdBookServiceImpl;

@Controller
public class AdBooksController {

    @Autowired
    private AdBookServiceImpl al;

     @RequestMapping("/upload")  
        public String upload(Books books,HttpServletRequest request,Model model) throws Exception{  
        System.out.println(request.getParameter("bookname"));  
          //儲存資料庫的路徑  
          String sqlPath = null;   
          //定義檔案儲存的本地路徑  
          String localPath="D:\\File\\";  
          //定義 檔名  
          String filename=null;    
          if(!books.getFile().isEmpty()){    
              //生成uuid作為檔名稱    
              String uuid = UUID.randomUUID().toString().replaceAll("-","");    
              //獲得檔案型別(可以判斷如果不是圖片,禁止上傳)    
              String contentType=books.getFile().getContentType();    
              //獲得檔案字尾名   
              String suffixName=contentType.substring(contentType.indexOf("/")+1);  
              //得到 檔名  
              filename=uuid+"."+suffixName;   
              System.out.println(filename);  
              //檔案儲存路徑  
              books.getFile().transferTo(new File(localPath+filename));    
          }  
          //把圖片的相對路徑儲存至資料庫  
          sqlPath = "/images/"+filename;  
          System.out.println(sqlPath);  
          //user.setId(1);
          books.setBookname(request.getParameter("bookname"));
          books.setPrice(Double.parseDouble(request.getParameter("price")));
          books.setStock(Integer.parseInt(request.getParameter("stock")));  
          books.setImg(sqlPath);  
          al.addBookService(books);
          model.addAttribute("books", books);  
          return "MyJsp";  
        }  
}

第六步:xml檔案(add圖書資訊)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.qut.mapper.AdBookDao">

    <!-- 增加圖書 -->
    <insert id="addBook" parameterType="com.qut.pojo.Books">
        INSERT INTO books(bookname,price,stock,img)
        values(#{bookname},#{price},#{stock},#{img})
    </insert>

</mapper>

第七步:JSP介面(test.jsp和MyJsp.jsp介面)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'test.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>

 <form action="upload.action" method="post" enctype="multipart/form-data">  
    <label>書名:</label><input type="text" name="bookname"><br>  
    <label>價格:</label><input type="text" name="price"><br>
    <label>庫存:</label><input type="text" name="stock"><br> 
    <label>上傳封面:</label><input type="file" name="file"><br>  
    <input type="submit">  
 </form>
  </body>
</html>
顯示如下圖

這裡寫圖片描述
這裡寫圖片描述