Springmvc第二讲学习笔记

1.所需额外jar包

commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
---------------------------
commons-logging-1.1.1.jar
jstl.jar
spring-aop-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
standard.jar




2.jsp页面

<body>
<form action="hello.do" method="post" enctype="multipart/form-data">
file:<br>
<input type="file" name="file"/><br>
<input type="file" name="file"/><br>
<input type="file" name="file"/><br>
<input type="submit" value="submit"/><br>
</form>
</body>



 

3.Springmvc配置文件,添加文件上传的配置,记不住,用到就复制

<bean id="multipartResolver"  
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置编码格式 -->  
<property name="defaultEncoding" value="utf-8"/>
<!-- 设置文件大小 -->  
         <property name="maxUploadSize" value="1048576000"/>
         <!-- 设置缓冲区大小 -->  
         <property name="maxInMemorySize" value="40960"/>  
</bean> 



4.Controller代码

@Controller
public class HelloController {
@SuppressWarnings("deprecation")
@RequestMapping("hello")
<!--还必须设置别名,页面的name="file"对应的Controller中的数组,是CommonsMultipartFile[]-->
public String hello(@RequestParam("file") CommonsMultipartFile[] file,

HttpServletRequest req) throws IOException {

//HttpServletRequest用于拿到fileUpload文件夹的在服务器中的路径

String path = req.getRealPath("/fileUpload");
InputStream is = null;
OutputStream os = null;
File uploadFile = null;
for (int i = 0; i < file.length; i++) {
is = file[i].getInputStream();//既然能让Controller接收到文件,那么这个文件一定有输入流为它服务.
uploadFile = new File(path, file[i].getOriginalFilename());
os = new FileOutputStream(uploadFile);
System.out.println(uploadFile.getPath());
int len = 0;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
is.close();
os.close();
}
return "/success.jsp";
}


}

猜你喜欢

转载自blog.csdn.net/weixin_41949977/article/details/82215630