文件上传

不是为了世界改变我们,而是世界不管变成什么样子,我们还是一样,保持最初的心。

文件上传

Servlet文件上传

 引jar包

<!--文件上传的jar包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>

<!-- 包扫描器 --> <!-- multipartResolver  是定值 不能是其他-->
<context:component-scan base-package="cn.happy.controllerfileupload"></context:component-scan>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<mvc:annotation-driven/>


@Controller
public class FirstController {
@RequestMapping("/first")
public String doFirst(MultipartFile upload, HttpSession session) {

//获取到用户上传的文件名称
String childpath = upload.getOriginalFilename();

//相对路径转换成绝对路径
String parenPath = session.getServletContext().getRealPath("/upload");

File filepath = new File(parenPath,childpath);
try {
upload.transferTo(filepath);
return "/WELCOME.jsp";

} catch (IOException e) {
e.printStackTrace();
return "/fileupload.jsp";
}


}

}
form要求

form要求:
<form method="post" enctype="multipart/form-data"> 多部分表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<h2>文件上传</h2>
<form action="/first" method="post" enctype="multipart/form-data">
文件 <input type="file" name="upload"/>
<input type="submit">
</form>
</body>
</html>
 






posted @ 2017-09-04 12:07  抱不住太阳的深海  阅读(131)  评论(0编辑  收藏  举报