Spring MVC實(shí)現(xiàn)文件上傳及優(yōu)化案例解析
前言
SpringMVC本身提高了便捷的文件上傳方式,接下來我將演示如何在SpringMVC中實(shí)現(xiàn)文件上傳的相關(guān)操作。以下案例是基于SSM框架整合的基礎(chǔ)上實(shí)現(xiàn)的文件上傳功能,如何進(jìn)行SSM整合,可以參考我以往的博客。
第一步:添加依賴
pom.xml
<!-- 文件上傳與下載-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>第二步:創(chuàng)建springmvc配置文件,添加文件上傳配置
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="com.csx"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"/>
<!--文件上傳 2.加配置,注意id-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans> 開啟掃描
開啟注解
配置視圖解析器
配置文件上傳相關(guān)配置
一定要配置id,不能省略,否則報(bào)錯(cuò)(底層根據(jù)id加載這個(gè)bean)
第三步:創(chuàng)建文件上傳頁面
up.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--文件上傳 3.寫頁面-->
<form action="/user/up.do" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file"> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
- 請(qǐng)求方式只能是post
- 注意添加enctype屬性
- 文件上傳的type為file,注意name屬性值要與controller層的參數(shù)名一致
第四步:寫controller,上傳到指定文件夾
UserController
package com.csx.controller;
import com.csx.entity.User;
import com.csx.service.UserService;
import com.csx.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/*文件上傳 4.寫controller,上傳至指定文件夾*/
@RequestMapping("/up")
public String fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
//創(chuàng)建文件夾,上傳文件
//獲得完整路徑
String realPath = request.getSession().getServletContext().getRealPath("/upload");
System.out.println("realPath===" + realPath);
//創(chuàng)建文件夾
File f = new File(realPath);
//如果文件夾不存在,就創(chuàng)建
if (!f.exists()) {
f.mkdirs();
}
//拿到上傳的文件名
String fileName = file.getOriginalFilename();
//將UUID和文件名拼接,防止文件名重名而覆蓋
fileName = UUID.randomUUID() + "_" + fileName;
//創(chuàng)建空文件
File newFile = new File(f, fileName);
//將文件內(nèi)容寫入
file.transferTo(newFile);
return "index";
}
}代碼解析
文件上傳,controller使用MultipartFile 類型進(jìn)行接收,并且參數(shù)名與頁面的屬性值保持一致
String realPath = request.getSession().getServletContext().getRealPath("/upload");
System.out.println("realPath===" + realPath);
//創(chuàng)建文件夾
File f = new File(realPath);
//如果文件夾不存在,就創(chuàng)建
if (!f.exists()) {
f.mkdirs();
}- 如果文件夾不存在,則創(chuàng)建文件夾upload
//拿到上傳的文件名 String fileName = file.getOriginalFilename(); //將UUID和文件名拼接,防止文件名重名而覆蓋 fileName = UUID.randomUUID() + "_" + fileName;
- 拿到原始文件名,并且使用UUID進(jìn)行覆蓋,防止上傳同名文件導(dǎo)致文件覆蓋
//創(chuàng)建空文件 File newFile = new File(f, fileName); //將文件內(nèi)容寫入 file.transferTo(newFile); return "index";
創(chuàng)建空文件,寫入內(nèi)容,返回Json格式數(shù)據(jù)
演示效果
地址欄輸入http://localhost:8080/up.html

點(diǎn)擊選擇文件,選擇第5.jpg


點(diǎn)擊提交

返回index,就是我們r(jià)eturn的String數(shù)據(jù),表示上傳成功,查看upload文件夾

文件上傳成功!
補(bǔ)充:實(shí)現(xiàn)局部刷新的異步登錄功能:優(yōu)化用戶體驗(yàn)的SpringMVC實(shí)踐
實(shí)現(xiàn)局部刷新的異步登錄功能:優(yōu)化用戶體驗(yàn)的SpringMVC實(shí)踐
前言
什么是異步刷新(局部刷新)
異步刷新是指在不重新加載整個(gè)網(wǎng)頁的情況下,僅更新頁面的某個(gè)部分。這通常通過AJAX(Asynchronous JavaScript and XML)技術(shù)實(shí)現(xiàn),AJAX允許網(wǎng)頁與服務(wù)器進(jìn)行異步通信,即在發(fā)送請(qǐng)求后無需等待服務(wù)器響應(yīng)即可完成其他任務(wù)。
案例實(shí)現(xiàn)
需求
如圖所示需求:

步驟
在SpringMVC中,實(shí)現(xiàn)異步刷新的步驟如下:
- 前端頁面:使用JavaScript(如jQuery)發(fā)送AJAX請(qǐng)求到服務(wù)器。這個(gè)請(qǐng)求可以包含需要更新的數(shù)據(jù)或指示服務(wù)器更新哪部分頁面的信息。
- SpringMVC控制器:控制器接收AJAX請(qǐng)求,處理請(qǐng)求中的數(shù)據(jù),并返回相應(yīng)的響應(yīng)。這個(gè)響應(yīng)可以是JSON、XML或其他格式的數(shù)據(jù),具體取決于前端頁面的需求。
- 前端頁面更新:當(dāng)AJAX請(qǐng)求成功返回時(shí),JavaScript使用返回的數(shù)據(jù)更新頁面的指定部分。這通常涉及使用DOM操作來修改頁面的內(nèi)容。
準(zhǔn)備工作
創(chuàng)建web項(xiàng)目,添加相關(guān)依賴,配置springmvc.xml和web.xml配置文件
登錄頁面
login.jsp
<%--
Created by IntelliJ IDEA.
User: 21038
Date: 2024/10/11
Time: 14:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="/js/jquery-1.8.3.js" type="text/javascript"></script>
</head>
<body>
<div>
<form id="frm" >
<table>
<tr>
<td>用戶名:<input type="text" id="user_name" name="user_name" value=""/></td>
<td>密碼:<input type="password" id="password" name="password" value=""/></td>
<td><input type="button" id="commit" value="登錄" /></td>
</tr>
<tr>
<td>
<span id="s1" ></span>
</td>
</tr>
</table>
</form>
<script>
var user="";
$(function () {
$("#commit").click(function () {
$.ajax({
type:'POST',
url:'/login.do',
data:$("#frm").serialize(),
success:function (res) {
user=res;
console.log(user)
if (user==""){
$("#s1").html("");
}else {
$("#s1").html("用戶:"+user+",歡迎登錄!");
}
$("#user_name").val("");
$("#password").val("");
}
});
});
});
</script>
</body>
</html>使用AJAX進(jìn)行異步提交數(shù)據(jù)到controller,并獲取響應(yīng)的Json格式數(shù)據(jù),接收到數(shù)據(jù)后,將數(shù)據(jù)填充到頁面指定位置。
控制器
LoginController
@RestController
public class LoginController {
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String LoginController(String user_name , String password ){
if ("admin".equals(user_name) && "123".equals(password)){
return user_name;
}
return "";
}
}測(cè)試
輸入賬戶:admin和密碼:123

點(diǎn)擊登錄按鈕,發(fā)送ajax請(qǐng)求

頁面異步刷新,獲取到后臺(tái)傳輸過來的數(shù)據(jù),并填寫到頁面中。
到此這篇關(guān)于Spring MVC實(shí)現(xiàn)高效文件上傳及優(yōu)化案例的文章就介紹到這了,更多相關(guān)Spring MVC文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringMVC實(shí)現(xiàn)文件上傳下載功能
- SpringMVC實(shí)現(xiàn)文件上傳與下載
- springmvc實(shí)現(xiàn)文件上傳功能
- SpringMVC 通過commons-fileupload實(shí)現(xiàn)文件上傳功能
- IDEA實(shí)現(xiàn) springmvc的簡(jiǎn)單注冊(cè)登錄功能的示例代碼
- Spring+SpringMVC+JDBC實(shí)現(xiàn)登錄的示例(附源碼)
- Spring mvc 實(shí)現(xiàn)用戶登錄的方法(攔截器)
- springmvc+shiro+maven 實(shí)現(xiàn)登錄認(rèn)證與權(quán)限授權(quán)管理
相關(guān)文章
java數(shù)組復(fù)制的四種方法效率對(duì)比
這篇文章主要介紹了java數(shù)組復(fù)制的四種方法效率對(duì)比,文中有簡(jiǎn)單的代碼示例,以及效率的比較結(jié)果,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
在Spring Boot中加載初始化數(shù)據(jù)的實(shí)現(xiàn)
這篇文章主要介紹了在Spring Boot中加載初始化數(shù)據(jù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
idea maven 構(gòu)建本地jar包及pom文件的過程
這篇文章主要介紹了idea maven 構(gòu)建本地jar包及pom文件的過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-11-11
Java 15密封接口的4個(gè)實(shí)現(xiàn)約束實(shí)戰(zhàn)指南
文章主要介紹了Java 15中密封接口的定義、使用、繼承約束以及在不同包和模塊中的訪問控制規(guī)則,密封接口通過限制類的繼承來提高類型安全性和封裝性,支持模式匹配和未來的switch表達(dá)式改進(jìn),感興趣的朋友跟隨小編一起看看吧2025-11-11

