spring mvc 文件上傳

??????????????????????????????????????????????????????????????????????????spring mvc 文件上傳??

一、單文件上傳

配置步驟:

步驟一、在配置文件中配置包掃描器(暫且這樣配,會出問題,我們下面說解決方案)

?

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--讓spring掃描包下所有的類,讓標注spring注解的類生效  --><context:component-scan base-package="cn.hmy.controller"/></beans>

?

步驟二,定制我們的文件上傳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>文件上傳</title></head><body><form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data"><h1>文件上傳</h1>文件:<input type="file" name="fileUpLoad"/></br><input type="submit" value="上傳"/>         </form></body>
</html>

步驟三、書寫我們的處理器代碼

package cn.hmy.controller;import java.io.File;
import java.io.IOException;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;import cn.hmy.pojo.UserInfo;@Controller
public class MyController{//處理器方法@RequestMapping(value="/list.do")    public void doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{//1.獲取文件名稱String filename = fileUpLoad.getOriginalFilename();//2.獲取文件的前半部分路徑String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路徑File file=new File(realPath,filename);//4.保存文件
         fileUpLoad.transferTo(file); }        
}

此時我們啟動服務器,進行代碼上傳,會報如下錯誤

?

解決方案:更改我們的spring-servlet.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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--讓spring掃描包下所有的類,讓標注spring注解的類生效  --><context:component-scan base-package="cn.hmy.controller"/>
<!--配置復雜類型表達解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean></beans>

啟動發現還是會報上述錯誤?

解決方案:配置注解驅動

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--讓spring掃描包下所有的類,讓標注spring注解的類生效  --><context:component-scan base-package="cn.hmy.controller"/>
<!--配置復雜類型表達解析器--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<!--配置注解驅動-->
<mvc:annotation-driven/> </beans>

如果在上述配置文件中缺少復雜類型解析器,會報如下錯誤

?

?

在解決了以上錯誤后,我們會發現如果我們上傳的文件中含有中文?? 會出現亂碼現象

解決亂碼

解決方案我們暫且提供以下兩種方式

方案一、

方案二、在web.xml中配置

<filter><filter-name>characterEncoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>

?

如何控制文件上傳大小

在spring-servlet.xml中配置如下

maxUploadSize為上傳的總文件的大小 5M
maxInMemorySize為上傳的單個文件的大小 1M
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="5000000"></property><property name="maxInMemorySize" value="1000000"></property></bean>

如果超出所限制的大小? 會報如下錯誤

?

?

控制文件上傳的類型(通過后綴名進行控制)在處理器中進行判定

例如 只允許上傳.jpg?? .png?? .gif為后綴的文件

package cn.hmy.controller;import java.io.File;
import java.io.IOException;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;import cn.hmy.pojo.UserInfo;@Controller
public class MyController{//處理器方法@RequestMapping(value="/list.do")    public String doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{//1.獲取文件名稱String filename = fileUpLoad.getOriginalFilename();//限定文件上傳的類型if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){//2.獲取文件的前半部分路徑String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路徑File file=new File(realPath,filename);//4.保存文件
             fileUpLoad.transferTo(file); }else{System.out.println("不支持上傳文件的類型");}return "/list.jsp";}        
}

?

?

?

如何判斷用戶沒用選上傳文件

?

?

多文件上傳

步驟一、

spring-servlet.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"xsi:schemaLocation="
        http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--讓spring掃描包下所有的類,讓標注spring注解的類生效  --><context:component-scan base-package="cn.hmy.controller"/><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="5000000"></property><property name="maxInMemorySize" value="1000000"></property></bean><mvc:annotation-driven/>
</beans>

?

步驟二、準備多文件上傳的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>文件上傳</title></head><body><form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data"><h1>文件上傳</h1>文件1:<input type="file" name="fileUpLoad"/></br>文件2:<input type="file" name="fileUpLoad"/></br>文件3:<input type="file" name="fileUpLoad"/></br><input type="submit" value="上傳"/>         </form></body>
</html>

步驟三、編寫處理器的代碼

 //多文件上傳@RequestMapping(value="/list.do")    public String doFirst2(@RequestParam MultipartFile[] fileUpLoad,HttpSession session) throws Exception{for (MultipartFile item : fileUpLoad) {//1.獲取文件名稱String filename = item.getOriginalFilename();//限定文件上傳的類型if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){//2.獲取文件的前半部分路徑String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路徑File file=new File(realPath,filename);//4.保存文件
                 item.transferTo(file); }else{System.out.println("不支持上傳文件的類型");}}return "/list.jsp";}

注意:在處理器方法中一定要對參數進行校對使用注解@RequestParam校正參數

丟到? 會報錯

即可實現多文件上傳

?

轉載于:https://www.cnblogs.com/hmy-1365/p/6104501.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/371969.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371969.shtml
英文地址,請注明出處:http://en.pswp.cn/news/371969.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用工廠模式解決設計問題

工廠設計模式是面向對象環境中最常用的模式之一。 再次來自“創意設計”模式類別&#xff0c;即有關對象創建的所有信息。 在某些情況下&#xff0c;對象的創建很復雜&#xff0c;可能需要某種程度的抽象&#xff0c;以便客戶端代碼無法意識到這些復雜性和內部實現細節。 在某些…

103. Binary Tree Zigzag Level Order Traversal

二刷。 BFS&#xff0c;基本習慣上用Iterative的做法來做&#xff0c;就是QUEUE。 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val x; }* }*/ public class Solution…

java多線程系列13 設計模式 Future 模式

Future 模式 類似于ajax請求 頁面異步的進行后臺請求 用戶無需等待請求的結果 就可以繼續瀏覽或者操作 核心就是&#xff1a;去除了主函數的等待時間&#xff0c;并使得原本需要等待的時間段可以用于處理其他業務邏輯 JDK內置實現Future模式演示一下 public class RealData im…

lodop轉到其他html頁面,Lodop實現打印功能

思路&#xff1a;1、在 html 頁面引入 LodopFuncs.js 文件&#xff0c;并用 object 標簽和 embed 標簽獲取 lodop 對象2、在 js 中獲取 html 頁面中的 object 和 embed 對象&#xff0c;并使用getLodop() 方法得到 lodop 對象3、實現打印功能&#xff0c;以下三步是必需的初始化…

完整的Web應用程序Tomcat JSF Primefaces JPA Hibernate –第3部分

Primefaces AutoComplete&#xff0c;JSF轉換器 這篇文章從第一部分和第二部分繼續。 JSF擁有Converter工具&#xff0c;可以幫助我們從用戶視圖中獲取一些數據并將其轉換為從數據庫或緩存中加載的對象。 在“ com.converter”包中&#xff0c;創建以下類&#xff1a; packa…

html5首屏加載樂山暴雨,發布前端項目時因chunk-vendors過大導致首屏加載太慢,Vue Build時chunk-vendors的優化方案...

這個優化是兩方面的&#xff0c;前端將文件打包成.gz文件&#xff0c;然后通過nginx的配置&#xff0c;讓瀏覽器直接解析.gz文件。1、compression-webpack-plugin插件打包.gz文件安裝插件npm install --save-dev compression-webpack-plugin或者yarn add compression-webpack-p…

width:100vh與min-height:calc(100vh + 51px)

vh:相對于視窗的高度&#xff0c;那么vw:則是相對于視窗的高度。 “視區”所指為瀏覽器內部的可視區域大小&#xff0c;即window.innerWidth/window.innerHeight大小&#xff0c;不包含任務欄標題欄以及底部工具欄的瀏覽器區域大小。 詳細vh的用法&#xff0c;大家可以參考http…

XML配置文件中的Spring配置文件

我的上一個博客非常簡單&#xff0c;因為它涵蓋了我從Spring 3.0.x到Spring 3.1.x的輕松升級&#xff0c;最后我提到可以將Spring模式升級到3.1&#xff0c;以利用Spring的最新功能。 在今天的博客中&#xff0c;我將介紹這些功能中最酷的功能之一&#xff1a;Spring配置文件。…

交大計算機專業怎樣,計算機專業高校實力排名,上海交大第五,清華第二,第一毫無爭議...

原標題&#xff1a;計算機專業高校實力排名&#xff0c;上海交大第五&#xff0c;清華第二&#xff0c;第一毫無爭議計算機專業在近幾年可謂是“大熱”&#xff0c;眾多考生搶破頭也想當碼農&#xff0c;背后的原因其實不難理解。互聯網時代的到來&#xff0c;計算機早已滲透到…

python_day7 綁定方法與非綁定方法

在類中定義函數如果 不加裝飾器 則默認 為對象作為綁定方法 如果增加 classmethod 是 以 類 作為綁定方法 增加 classmethod 是 非綁定方法&#xff0c;就是不將函數 綁定 ##################### class Foo: def func(self): print(self) classmethod def func…

Spring Security使用Hibernate實現自定義UserDetails

大多數時候&#xff0c;我們將需要在Web應用程序中配置自己的安全訪問角色。 這在Spring Security中很容易實現。 在本文中&#xff0c;我們將看到最簡單的方法。 首先&#xff0c;我們將在數據庫中需要以下表格&#xff1a; CREATE TABLE IF NOT EXISTS mydb.security_role (…

python之路-面向對象

編程范式 編程是 程序 員 用特定的語法數據結構算法組成的代碼來告訴計算機如何執行任務的過程 &#xff0c; 一個程序是程序員為了得到一個任務結果而編寫的一組指令的集合&#xff0c;正所謂條條大路通羅馬&#xff0c;實現一個任務的方式有很多種不同的方式&#xff0c; 對這…

西安郵電大學計算機科學與技術有專碩嗎,2020年西安郵電大學計算機學院考研擬錄取名單及排名!...

20考研復試調劑群&#xff1a;4197552812020年西安郵電大學計算機學院碩士研究生招生復試成績及綜合排名各位考生&#xff1a;現將我院2020年碩士研究生招生復試成績及綜合排名公布(最終錄取名單及新生學籍注冊均以“全國碩士研究生招生信息公開平臺”備案信息為準)&#xff0c…

用Java排序的五種有用方法

Java排序快速概述&#xff1a; 正常的列表&#xff1a; private static List VEGETABLES Arrays.asList("apple", "cocumbers", "blackberry");Collections.sort(VEGETABLES);output: apple, blackberry, cocumbers反向排序&#xff1a; pri…

[python]-數據科學庫Numpy學習

一、Numpy簡介&#xff1a; Python中用列表(list)保存一組值&#xff0c;可以用來當作數組使用&#xff0c;不過由于列表的元素可以是任何對象&#xff0c;因此列表中所保存的是對象的指針。這樣為了保存一個簡單的[1,2,3]&#xff0c;需要有3個指針和三個整數對象。對于數值運…

檢測一個點, 是否在一個半圓之內的方法

demo: http://jsbin.com/lihiwigaso 需求: 一個圓分成分部分, 鼠標滑上不同的區域顯示不同的顏色 思路: 先判斷這個點是否在圓之內, 再判斷是否在所在的三角形之內就可以了 所需要的全部源碼: <!DOCTYPE html> <html> <head><meta charset"utf-8&quo…

計算機網絡設備接地規范,網絡機房防雷接地的四種方式及靜電要求

編輯----河南新時代防雷由于計算機網絡系統的核心設備都放置在網絡機房內&#xff0c;因而網絡機房防雷接地有了較高的環境要求&#xff0c;良好的接地系統是保證機房計算機及網絡設備安全運行&#xff0c;以及工作人員人身安全的重要措施。直流地的接法通常采用網格地&#xf…

抓住尾部的StackOverFlowError

使用Java程序時可能要處理的一種更煩人的情況是StackOverFlowError&#xff0c;如果您有一個很好的可生產的測試用例&#xff0c;那么關于使用堆棧大小或設置條件斷點/某種痕跡 。 但是&#xff0c;如果您有一個測試案例可能一次失敗100次&#xff0c;或者像我的案例一樣在AWTM…

Gunicorn配置部分的翻譯

寫在前面&#xff0c;雖然翻譯得很爛&#xff0c;但也是我的勞動成果&#xff0c;轉載請注明出處&#xff0c;謝謝。 Gunicorn版本號19.7.1 Gunicorn配置 概述 三種配置方式 優先級如下&#xff0c;越后的優先級越大 1.框架的設置&#xff08;現在只有paster在用這個&#xff0…

臺式計算機風扇聲音大怎么處理,如何解決電腦電源風扇聲音大的問題?

現在的臺式機一般用3到5年后&#xff0c;一些問題自然也就慢慢表現出來了。很多網友在使用電腦過程中都有電腦風扇聲音大怎么辦的問題&#xff0c;電腦風扇聲音大就會讓人覺得使用電腦很不舒服&#xff0c;怎么辦好呢&#xff1f;出現重要的問題要如何解決好呢&#xff1f;現在…