spring 文件上传
首先文件上传需要的配置相比之前又增加啦一些,主要是在pom.xml和spring.xml中
在pom.xml中增加的:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
在spring.xml增加的是:
<!-- 文件上传所需要的配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
接下来就是创建一个类开始书写代码,也是需要一个jsp,和一个class文件
首先是jsp中的代码
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name = "file">
<input type="submit">
</form>
</body>
//enctype="multipart/form-data是固定的写法
接下来是类的
@Controller
public class UploadContrller {
@RequestMapping(value = "upload" ,method= RequestMethod.POST)
public void upload(@RequestParam(value="file") MultipartFile file,
HttpServletRequest req,HttpServletResponse resp
){
try {
InputStream in = file.getInputStream();
String path = req.getServletContext().getRealPath("/upload/test.jpg");
File f = new File(path);
System.out.println(f.getAbsolutePath());
FileOutputStream out = new FileOutputStream(f);
IOUtils.copy(in, out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resp.getWriter().print("上传成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这样就完成啦文件上传,希望对大家有所帮助,代码路远,仍在学习中,,,