網(wǎng)站首頁 編程語言 正文
文章目錄
- 前言
- 一、準(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
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2023-04-04 iOS數(shù)據(jù)持久化UserDefaults封裝器使用詳解_IOS
- 2023-06-17 go開源Hugo站點(diǎn)渲染之模板詞法解析_Golang
- 2022-04-08 詳解RIFF和WAVE音頻文件格式_相關(guān)技巧
- 2021-12-19 詳細(xì)易懂注解,二維數(shù)組楊輝三角的實(shí)現(xiàn),算法入門
- 2022-08-22 優(yōu)雅使用GoFrame共享變量Context示例詳解_Golang
- 2023-12-12 設(shè)置線程名稱(兩種方法)
- 2023-10-09 mobx中react的觀察者
- 2023-07-13 react中的useRef的使用
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支