天天看点

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";