天天看點

springmvc.實作檔案上傳|學習筆記springmvc.實作檔案上傳

開發者學堂課程【SpringMVC架構入門:springmvc.實作檔案上傳】學習筆記,與課程緊密聯系,讓使用者快速學習知識。

課程位址: https://developer.aliyun.com/learning/course/22

springmvc.實作檔案上傳

目錄:

一.通過commons-fileupload.來實作。

二.配置springmvc的配置解析器

三.jsp頁面

四.Controller 代碼

五.批量上傳的代碼

1.通過commons-fileupload.來實作。

導入相關jar包:commons-fileupload,commons-io;

2.  配置springmvc的配置解析器。

<bean id= "multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name= "DefaultEncoding"

value="utf-8"></property>

<property name= "maxUploadSize"

value="10485760000"></property>

<property name="maxInMemorySize"

value="40960"></property>

</bean>

3.jsp頁面

<form action= "upload.do"method="post"

enctype="multipart/form-data">

file:<input type="file"name="file"/<input type="submit"value="上傳"/>

</ form>

</body>

4.Controller 代碼

@Controller

public class FileuploadController, {

@ReguestMapping("/upload")

public String

fileupload(@RequestParam("file")ÇommonsMultipartFilefile,HttpServletRequest,reg) throws I0Exception{

//擷取檔案名

//file,get0riginalEilename();

//擷取上傳檔案的路徑

String path =reg. getRealPath("/fileueload");

InputStream is= file. getInputStream();

OutputStream os = new FileOutputStream (new

File(path,file.get0riginalFilename()));

int,len=0;

byte[] buffer = new byte[400];

while((len=is,read(buffer))!=-1)

os.write(buffer,0,len);

os.close();

is.close();

return "/index.isp" ;

}

注釋:RequestParam 這個是重點;

5.批量上傳的代碼

@ReauestMapping("/batch")

public String

fileupload(@Regues.tParam("file")CommonsMultipartFile

file[] ,HttpServletReguest reg) throws IOException{

//file.getrisinalFilename();

String path = reg, getRealPathf"(/fileupload");

for(int i=0;i<file.length;i++){

InputStream is = file[i] . getInputStream();

OutputStream os= new FileOutputStream(new

File(path,file[i].getOriginalFilename()));

int len=0; ,

while( (len=is.read(buffer))!=-1)

os..write(buffer, 0, len);

return"/index.isp";