springmvc文件上传

本文介绍如何使用Spring MVC框架实现文件上传功能,包括所需依赖、配置文件解析、页面构建及控制器编写等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.jar commons-fileupload-1.2.2.jar

         commons-io-2.0.1.jar

2.xml文件中添加

  <!-- 支持上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

3.构建页面

uploadFile.jsp

  <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="<%=this.getServletContext().getContextPath() %>/test/uploadfile.html" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="uploadFile" />
<input type="submit" value="上传"/>
</form>
</body>
</html>


success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传成功</title>
</head>
<body>
<h1>上传文件成功!</h1>
<img alt="" src="${fileUrl }" />
</body>
</html>


error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传失败</title>
</head>
<body>
<h1>上传文件失败!</h1>
</body>
</html>

4.controll类编写

@Controller
@RequestMapping(value = "/test")
public class UploadFileController {
	
	@RequestMapping("toUploadFile")
	public String toUpload(){
		return "test/uploadFile";
	}
	
	@RequestMapping("success")
	public String toSuccess(){
		return "test/success";
	}
	
	@RequestMapping("error")
	public String toError(){
		return "test/error";
	}

	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public String uploadFile(
			@RequestParam(value = "uploadFile", required = true) MultipartFile file,
			HttpServletRequest request) {
		System.out.println("开始");
		String path = request.getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		System.out.println(path);
		File targetFile = new File(path, fileName);

		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
			request.getSession().setAttribute("fileUrl",
					request.getContextPath() + "/upload/" + fileName);
			return "redirect:success.html";
		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:error.html";
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值