##上傳檔案 spring框架
####1、建立web頁面
檔案上傳的html頁面中需要表單,且method="post
和enctype="multipart/form-data"
,使用的控制項是:
####2. 新增依賴method
="post"
action
="upload.do"
enctype
="multipart/form-data"
>
>
name
="file"
type
="file"
/>
div>
>
type
="submit"
value
="上傳"
/>
div>
form
>
springmvc中的檔案上傳依賴apache的commons-fileupload
,所以,新增依賴:
####3. 配置commonsmultipartresolver
>
>
commons-fileuploadgroupid
>
>
commons-fileuploadartifactid
>
>
1.3.3version
>
dependency
>
使用springmvc的上傳,必須在spring的配置檔案中配置commonsmultipartresolver
,且id
必須是multipartresolver
,該節點可以有更多配置,也可以不新增配置,最簡化配置如下:
"multipartresolver"
class
="org.springframework.web.multipart.commons.commonsmultipartresolver"
/>
通常,上傳的檔案都必須限制檔案型別,可以通過@controller
public
class
uploadcontroller
}
commonsmultipartfile
物件的string getcontenttype()
方法獲取檔案的mime型別,例如image/jpeg
,更多型別可以在tomcat的conf/web.xml
中查詢。
且上傳的檔案必須限制檔案大小,因為過大的檔案可能導致上傳體驗較差,並且,產生的流量消耗較大,占用較多的伺服器端儲存空間,通過commonsmultipartfile
物件的long getsize()
方法可以獲取檔案的大小,例如12345,是以位元組為單位的。
還可以通過commonsmultipartfile
物件的string ``getoriginalfilename()
方法獲取源檔名,即使用者端的檔名,主要通過該檔名截取出檔案的副檔名,用於最終儲存檔案。
最終儲存的檔名應該自定義命名規則,以保證每個使用者上傳的檔案彼此不會覆蓋,通常會使用時間、隨機數等作為檔名的某個部分。
除此以外,還可以通過getbytes()
和getinputstream()
獲取使用者上傳的原始資料/流,然後自行建立輸出流,將資料寫入到伺服器端的檔案中,而自定義輸出流的寫入,可以根據實際情況提高寫入效率!
關於在spring的配置檔案中配置的commonsmultipartresolver
,可以配置以下屬性:
注意:在html頁面中,在標籤中新增
multiple="multiple"
,則上傳時可以同時選中多個檔案提交上傳,且,在伺服器端處理時,處理請求的方法中應該宣告commonsmultipartfile files
引數來接收多個檔案的資料。
spring檔案上傳
案例1關於上傳檔案 首先在myspring servlet.xml配置檔案中新增上傳元件 class org.springframework.web.multipart.commons.commonsmultipartresolver 具體案例參考 upload檔案 這裡值得我們注意的是上傳中文會亂...
spring檔案上傳
1 配置對上傳檔案大小的限制 id multipartresolver class org.springframework.web.multipart.commons.commonsmultipartresolver name defaultencoding value utf 8 name max...
Spring檔案上傳
size medium color olive 檔案上傳可以使用普通的表單提交,也可以使用ajax非同步提交,如果需要使用ajax提交則需要引入juery.form.js。1 普通的表單提交檔案上傳 color size characterencoding org.springframework.w...