SpringMVC中文件的上传

SpringMVC中文件的上传

一.

pom.xml中添加依赖

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.1</version>

</dependency>

.

springmvc.xml中配置如下

<!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->

<bean id="multipartResolver"

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

<property name="maxUploadSize" value="209715200" />

<property name="defaultEncoding" value="UTF-8" />

<property name="resolveLazily" value="true" /><!--延迟加载提高性能-->

</bean>

三.

前端页面:

<center>

<div style="width:420px;">

<form action="<%=request.getContextPath() %>/hello/doupload" method="post"  enctype="multipart/form-data">

<fieldset>

<legend>文件上传</legend>

<input type="file" name="file"/>

<input type="submit"  value="upload">

</fieldset>

</form>

</div>

</center>

四:

Controller层:

@Controller

@RequestMapping("/hello")

public class HelloMvcController {

@RequestMapping(value="/doupload",method=RequestMethod.POST)

public String doUpload(@RequestParam("file")MultipartFile file) throws IOException{//使用注解与表单中的file相关联

  if(!file.isEmpty()){//判断文件是否为空

  //将文件保存到指定位置

    String localPath = "c:\\testImgPath\\imooc\\";//想要保存到的本地路径

    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(localPath,System.currentTimeMillis()+file.getOriginalFilename()));

  }

  return "success";

}

}

然后,我们会发现在c:\\testImgPath\\imooc\\下有了一个文件:

至此,SpringMVC下的文件上传成功实现!

猜你喜欢

转载自www.cnblogs.com/boluo-code/p/10611556.html