日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

適用SpringMVC實(shí)現(xiàn)圖片上傳功能

作者:鑄鍵為犁 更新時間: 2023-07-25 編程語言

文章目錄

  • 前言
  • 一、準(zhǔn)備工作和實(shí)現(xiàn)步驟
  • 二、代碼編寫
    • 1.導(dǎo)入依賴
    • 2.編寫springmvc.xml配置
    • 3.搭建JSP頁面
    • 4.編寫控制層
    • 5.編寫一個上傳成功的頁面,并實(shí)現(xiàn)下載功能
    • 6.測試
  • 總結(jié)


前言

圖片上傳是一個在實(shí)際開發(fā)中經(jīng)常遇到的業(yè)務(wù)場景,本次就來學(xué)習(xí)一下圖片上傳。


一、準(zhǔn)備工作和實(shí)現(xiàn)步驟

  • 使用IDEA新建一個maven項目
  • 并導(dǎo)入相關(guān)依賴
  • 完善項目結(jié)構(gòu)
  • 搭建前端頁面
  • 配置靜態(tài)資源處理
  • 編寫后端controller
  • 測試

二、代碼編寫

1.導(dǎo)入依賴

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.lzl</groupId>
  <artifactId>UploadDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>UploadDemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- springmvc依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!-- lombok注解依賴 -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.3</version>
    </dependency>
    <!--文件上傳-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <!--servlet  需要這個依賴  并且 tomcat8 版本 要不會有 request 轉(zhuǎn)換異常-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    <!-- 資源編譯至target目錄配置 -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>*.xml</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

</project>

2.編寫springmvc.xml配置

<beans 	xmlns="http://www.springframework.org/schema/beans"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mvc="http://www.springframework.org/schema/mvc"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
							http://www.springframework.org/schema/beans/spring-beans.xsd
							http://www.springframework.org/schema/context
							http://www.springframework.org/schema/context/spring-context.xsd
							http://www.springframework.org/schema/mvc
							http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 告知springmvc  哪些包中 存在 被注解的類 springmvc取代的是servlet,所以只掃描controller -->
    <context:component-scan base-package="com.lzl.controller"></context:component-scan>
    <!-- 注冊注解開發(fā)驅(qū)動 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 視圖解析器
         作用:1.捕獲后端控制器的返回值="index"
              2.解析: 在返回值的前后 拼接 ==> "/index.jsp"
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前綴 -->
        <property name="prefix" value="/"></property>
        <!-- 后綴 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--文件上傳配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
    </bean>
    <!-- 靜態(tài)資源訪問 -->
    <mvc:default-servlet-handler/>
</beans>

3.搭建JSP頁面

我們需要一個上傳圖片的按鈕和文件域
代碼如下(示例):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>圖片上傳</title>
</head>
<body>
這是圖片上傳界面
<form action="/upload" enctype="multipart/form-data" method="post">
    請選擇要上傳的文件:<input type="file" name="upload"/><br />
    <input type="submit" value="上傳">
</form>
</body>
</html>

需要注意的是,form表單的enctype屬性必須設(shè)置為multipart/form-data,提交方式必須選擇post

4.編寫控制層

我們需要接收jsp表單傳輸過來的文件類型對象,所以后端接收參數(shù)需要使用MultipartFile 這個類

@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile upload, HttpServletRequest request) throws IOException {
        System.out.println(upload);
        String filename = upload.getOriginalFilename();
        String realPath =  request.getServletContext().getRealPath("/");
        File uploadDir = new File(realPath,"upload");
        if(!uploadDir.exists()){
            uploadDir.mkdirs();//如果沒有目錄就創(chuàng)建
        }
        // 底層 是 IO 流操作
        upload.transferTo(new File(uploadDir,filename));

        request.setAttribute("result","上傳成功");
        // 得到上傳的目錄下的 所有文件的名字  放在集合 傳到頁面以超鏈接的形式展示  進(jìn)行下載
        String[] list = uploadDir.list();

        List<String> fileNames = Arrays.asList(list);
        request.setAttribute("fileNames",fileNames);
        return "result";
    }
   
}

5.編寫一個上傳成功的頁面,并實(shí)現(xiàn)下載功能

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false" %>
<html>
<head>
  <title>成功頁面</title>
</head>
<body>
${result} <br>
<%=request.getAttribute("result") %>
<c:forEach var="file" items="${fileNames}">
  <img src="${pageContext.request.contextPath}/upload/${file}"/>
  ${file} <a href="${pageContext.request.contextPath}/download?filename=${file}">下載</a>
</c:forEach>
</body>
</html>

后端的controller

@RequestMapping("/download")
    public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 設(shè)置響應(yīng)頭告訴瀏覽器以何種方式處理響應(yīng)
        response.setHeader("content-disposition","attachment;filename="+filename);

        System.out.println(filename);

        ServletOutputStream outputStream = response.getOutputStream();

        String path = request.getServletContext().getRealPath("/upload");

        File file = new File(path, filename);

        byte[] bytes = FileUtils.readFileToByteArray(file);

        outputStream.write(bytes);

        outputStream.close();
    }

6.測試

總結(jié)

本次圖片上傳只是一個最為原始的實(shí)現(xiàn)思路,實(shí)際開發(fā)中會有比這更好的實(shí)現(xiàn)思路

原文鏈接:https://blog.csdn.net/l_zl2021/article/details/127242717

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新