SSM上傳圖片并保存圖片地址到數(shù)據(jù)庫(kù)

說(shuō)出來(lái)有點(diǎn)不好意思,還沒(méi)寫過(guò)上傳圖片的功能。最近接的一個(gè)外包項(xiàng)目因?yàn)橛幸玫竭@個(gè)功能,所以打算使用SSM實(shí)現(xiàn)圖片上傳的功能,上傳好后把圖片地址保存到數(shù)據(jù)庫(kù),同時(shí)在前端顯示圖片。

使用maven構(gòu)建項(xiàng)目,首先導(dǎo)入相關(guān)的jar,這里就放上傳文件的jar配置,不然篇幅太長(zhǎng)了,其他的還有spring相關(guān)的,mybatis,日志的,數(shù)據(jù)庫(kù)的,包括servlet和jstl相關(guān)的。

      <!-- 文件上傳的jar包 -->
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
      </dependency>
      <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
      </dependency>

配置好pom.xml后,接下來(lái)就是web.xml,只需要配置dispatcherServlet就行。

項(xiàng)目目錄結(jié)構(gòu)

接下來(lái)就是新建數(shù)據(jù)表

DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `pimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`pid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

然后就是那一大堆配置文件,我就不寫了,要注意的是在spring-web.xml中配置文件上傳解析器

        <!-- 文件上傳的解析器 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 上傳圖片的最大尺寸 10M-->
            <property name="maxUploadSize" value="10485760"></property>
            <!-- 默認(rèn)編碼 -->
            <property name="defaultEncoding" value="utf-8"></property>
        </bean>

緊接著是mapper文件的編寫,主要有兩個(gè)sql,一個(gè)是圖片上傳,另一個(gè)是選擇所有圖片

    <mapper namespace="com.codeliu.dao.ProductDao">
        <!-- 查詢所有圖片 -->
        <select id="list" resultType="product">
            select pid, pimage from product
        </select>
        
        <insert id="save" parameterType="product">
            insert into product(pimage) values(#{pimage})
        </insert>
    </mapper>

接下來(lái)就是pojo,dao,service,controller類的編寫

首先pojo

public class Product implements Serializable {

    private Integer pid;
    
    private String pimage;

    // set、get方法
}

其次dao

public interface ProductDao {
    
    /**
     * 查詢所有的圖片
     * @return
     */
    List<Product> list();
    
    /**
     * 上傳一張圖片
     * @param product
     * @return
     */
    Integer save(Product product);
}

接著是service

@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductDao productDao;

    @Override
    public List<Product> list() {
        return productDao.list();
    }

    @Override
    @Transactional
    public String save(MultipartFile file, Product product, ModelMap map) throws IOException {
        
        // 保存圖片的路徑,圖片上傳成功后,將路徑保存到數(shù)據(jù)庫(kù)
        String filePath = "F:\\upload";
        // 獲取原始圖片的擴(kuò)展名
        String originalFilename = file.getOriginalFilename();
        // 生成文件新的名字
        String newFileName = UUID.randomUUID() + originalFilename;
        // 封裝上傳文件位置的全路徑
        File targetFile = new File(filePath, newFileName);
        file.transferTo(targetFile);    
        
        // 保存到數(shù)據(jù)庫(kù)
        product.setPimage(newFileName);
        productDao.save(product);
        return "redirect:/listImages";
    }

}

最后是controller

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @RequestMapping("/listImages")
    public ModelAndView list(Model model) {
        List<Product> lists = productService.list();
        ModelAndView mav = new ModelAndView();
        mav.addObject("lists", lists);
        mav.setViewName("list");
        System.out.println(lists);
        return mav;
    }
    
    /**
     * 保存圖片
     * @param file
     * @param product
     * @param map
     * @return
     */
    @RequestMapping("/save")
    public String save(MultipartFile file, Product product, ModelMap map) {
        try {
            return productService.save(file, product, map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

上傳圖片的邏輯在service里面,注釋很清楚,相信一看就能明白,接著寫兩個(gè)jsp頁(yè)面,一個(gè)用于上傳,一個(gè)用于顯示。

<body>
    <form action="save" method="post" enctype="multipart/form-data">
        圖片:<input type="file" name="file"><br>
        <input type="submit" value="提交">
    </form>
</body>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" />
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>list</title>
<style type="text/css">
    #images{
        width: 150px;
        height: 250px;
    }
</style>
</head>
<body>
    
    <table class="table table-bordered table-hover">
        <tr>
            <th>序號(hào)</th>
            <th>圖片</th>
        </tr>
        <c:forEach items="${lists}" var="product">
            <tr>
                <td>${product.pid}</td>
                <td>
                    <c:if test="${product.pimage != null}">
                        <img alt="" src="/image/${product.pimage}" id="images">
                    </c:if>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

做好了上面的這些,還需要指定圖片上傳的位置,直接在tomcat中指定


萬(wàn)事俱備,只欠東風(fēng)了。接下來(lái)就啟動(dòng)項(xiàng)目,輸入localhost:8080/SSM_uploadImage/index.jsp,就可以選擇圖片進(jìn)行上傳,上傳之后,可以看到數(shù)據(jù)庫(kù)已經(jīng)插入了一條記錄,同時(shí)指定的目錄下已經(jīng)有圖片了。

4.png

跳轉(zhuǎn)到list.jsp,顯示圖片

5.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 對(duì)于java中的思考的方向,1必須要看前端的頁(yè)面,對(duì)于前端的頁(yè)面基本的邏輯,如果能理解最好,不理解也要知道幾點(diǎn)。 ...
    神尤魯?shù)婪?/span>閱讀 901評(píng)論 0 0
  • title: SSM注解開(kāi)發(fā)的高級(jí)知識(shí)講解tags: SSMcategories: SSM 若圖片無(wú)法顯示,請(qǐng)前往...
    codingXiaxw閱讀 1,912評(píng)論 0 17
  • 不知何時(shí)開(kāi)始,我害怕騎車的人。就像我們不知道時(shí)間都流向了何處,只會(huì)越來(lái)越容易感覺(jué)到疲憊。 我害怕騎車的人。 和他們...
    章愷之閱讀 483評(píng)論 0 0
  • 我一向不喜歡主動(dòng)和人聯(lián)系,所以身邊的朋友不多。 昨天吃完晚飯后在家看電視,突然接到電話,是阿芳打來(lái)的,心里頭第一個(gè)...
    小驀閱讀 388評(píng)論 4 1
  • 今天領(lǐng)導(dǎo)把我手里的工作,關(guān)于做周報(bào)和數(shù)據(jù)統(tǒng)計(jì)的都交給他人,是比我晚了一個(gè)月的同事。頓時(shí)覺(jué)得輕松了很多,雖然說(shuō)是周五...
    Jiang江柳閱讀 234評(píng)論 0 0

友情鏈接更多精彩內(nèi)容