SpringMVC(四)SpringMVC檔案上傳

2021-10-03 07:02:24 字數 2946 閱讀 3061

method 屬性取值必須是 post

提供乙個檔案選擇域< input type=」file」 /> 名稱

作用string getoriginalfillename()

返回客戶端提交的原始檔名稱

void transferto(file destination)

將上傳檔案儲存到目標目錄下

string getcontenttype()

返回檔案的內容型別

string getname()

返回請求引數的名稱

boolean isempty()

判斷被上傳檔案是否為空

首先匯入commons-fileupload相關jar包

commons-fileupload<

/groupid>

commons-fileupload<

/artifactid>

1.3.1

<

/version>

<

/dependency>

commons-io<

/groupid>

commons-io<

/artifactid>

2.4<

/version>

<

/dependency>

編寫jsp頁面模擬表單上傳

編寫控制器

@controller

public

class

fileuploadcontroller

// 獲取上傳檔案的名稱

string filename = uploadfile.

getoriginalfilename()

;// 把檔案的名稱設定唯一值,uuid

string uuid = uuid.

randomuuid()

.tostring()

.replace

("-",""

);filename = uuid+

"_"+filename;

//上傳檔案

uploadfile.

transferto

(new

file

(path,filename));

return

"success"

;//返回結果到success.jsp

}}

在springmvc.xml配置檔案解析器

"multipartresolver"

class

="org.springframework.web.multipart.commons.commonsmultipartresolver"

>

<

!-- 設定上傳檔案的最大尺寸為10m--

>

"maxuploadsize" value=

"10485760"

/>

"defaultencoding" value=

"utf-8"

/>

<

/bean>

注意:檔案上傳的解析器 id是固定的,不能起別的名稱,否則無法實現請求引數的繫結。

在tomcat中配置允許寫操作,即修改conf目錄下的web.xml檔案,新增內容:

注意:一定要重啟 tomcat伺服器

首先建立乙個新的web專案,用來接收上傳檔案,在idea中新增乙個tomcat伺服器,修改埠號,新增新建的專案

在pom.xml中匯入相關jar包

com.sun.jersey<

/groupid>

jersey-core<

/artifactid>

1.18

.1<

/version>

<

/dependency>

com.sun.jersey<

/groupid>

jersey-client<

/artifactid>

1.18

.1<

/version>

<

/dependency>

編寫jsp頁面

編寫控制器 (

"/fileupload2"

)public string fileupload2

(multipartfile uploadfile)

throws exception

配置解析器

SpringMVC學習筆記之與Spring的關係

需要進行 spring 整合 springmvc 嗎 還是否需要再加入 spring 的 ioc 容器嗎 是否需要再 web.xml 檔案中配置啟動 spring ioc 容器 contextloaderlistener 嗎 需要 通常情況下,類似於資料來源 事務 整合其它框架都是放在spring ...

通過HelloSpring了解Spring的IOC

在dao層建立乙個hello實體類。package dao public class hello public void setstr string str override public string tostring 然後要輸出就要建立物件,在spring中,有乙個ioc池,需要使用物件就在池裡...

Spring MVC學習筆記(四)

pointcut execution concert.performance.perform 定義命名的切點,為 pointcut註解設定的值是乙個切點表示式,通過在performance方法上新增 pointcut註解,我們實際上擴充套件了切點表示式語言,這樣就可以在任何的切點表達中使用perfo...