spring mvc 怎么实现上传文件
1个回答
展开全部
在springmvc配置文件中这样配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 编码设置 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小 -->
<property name="maxUploadSize" value="-1"/>
<!--推迟文件解析,以便在UploadAction中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
页面:
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" />
<input type="submit" value="上传" />
</form>
后台:
@Controller
public class UploadAction implements ServletContextAware {
private ServletContext context;
@RequestMapping("/upload")
public String upload(HttpServletRequest request) throws Exception{
//转换请求为文件上传请求
MultipartHttpServletRequest mrequest=(MultipartHttpServletRequest)request;
MultipartFile mfile=mrequest.getFile("file");
if(!mfile.isEmpty()){//判断文件是否为空
path=context.getRealPath("/upload")+File.separator+mfile.getOriginalFilename();
File file=new File(path);
mfile.transferTo(file);//保存文件
}
return "跳转页面";
}}
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 编码设置 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小 -->
<property name="maxUploadSize" value="-1"/>
<!--推迟文件解析,以便在UploadAction中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
页面:
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" />
<input type="submit" value="上传" />
</form>
后台:
@Controller
public class UploadAction implements ServletContextAware {
private ServletContext context;
@RequestMapping("/upload")
public String upload(HttpServletRequest request) throws Exception{
//转换请求为文件上传请求
MultipartHttpServletRequest mrequest=(MultipartHttpServletRequest)request;
MultipartFile mfile=mrequest.getFile("file");
if(!mfile.isEmpty()){//判断文件是否为空
path=context.getRealPath("/upload")+File.separator+mfile.getOriginalFilename();
File file=new File(path);
mfile.transferTo(file);//保存文件
}
return "跳转页面";
}}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询