spring protlet MVC 上传文件

本文介绍了一个使用Spring框架实现文件上传的例子,详细展示了从页面表单到后台处理的全过程,包括配置文件设置、控制器方法及文件保存的具体实现。

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

上传页面jsp:

<form:form id="form1" name="form1" method="post"
			action="${turnToSaveOutcomeViewURL}" enctype="multipart/form-data">
			<table style="text-align: center; width: 100%;">
				<tr>
					<td class="tdRight">
						上传文件:
					</td>
					<td class="tdLeft">
						<input type="file" id="attachment" name="attachment" />
					</td>
				</tr>
				<tr>
					<td class="tdCenter" colspan="2">
						<a id="submitBtn1" class="majorButton"><span>提交</span> </a>
					</td>
				</tr>
			</table>
</form:form>


ApplicationContext.xml配置文件中的代码配置:

	<!-- 处理文件上传  portlet multipart resolver 2012-08-02-->
	<bean id="portletMultipartResolver"
		class="org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver">
		<property name="maxUploadSize" value="10000000" />
	</bean>


Controller中代码部分:

	@RequestMapping(params = "action=turnToSaveOutcomeView")
	public void turnToSaveOutcomeView(ActionRequest request,
			ActionResponse response) throws IOException {
		System.out.println(this.getClass() + " void turnToSaveOutcomeView()");
		// 上传文件程序段开始================================================================
		// 转型为MultipartHttpRequest
		DefaultMultipartActionRequest multipartRequest = (DefaultMultipartActionRequest) request;
		// 根据前台的name名称得到上传的文件
		MultipartFile file = multipartRequest.getFile("attachment");
		// 获得文件名:
		String realFileName = file.getOriginalFilename();
		System.out.println("获得文件名:" + realFileName);
		// 获取路径
		String ctxPath = request.getContextPath();
		ctxPath = request.getPortletSession().getPortletContext().getRealPath(
				"/")+"uploadFile\\";
		System.out.println("路径:" + ctxPath);
		// 创建文件
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()) {
			dirPath.mkdir();
		}
		String newFileName = (new Date()).getTime() + realFileName.substring(realFileName.indexOf("."));
		
		File uploadFile = new File(ctxPath + newFileName);
		FileCopyUtils.copy(file.getBytes(), uploadFile);
		// 上传文件程序段结束================================================================

		response.setRenderParameter("info", "保存成功");
		response.setRenderParameter("action", "turnToSaveOutcomeView");
	}

	@RequestMapping(params = "action=turnToSaveOutcomeView")
	public ModelAndView turnToSaveOutcomeView(RenderRequest request,
			RenderResponse response, String info) {
		System.out.println(this.getClass()
				+ " ModelAndView turnToSaveOutcomeView()");
		ModelAndView mv = new ModelAndView();
		mv.addObject("info", info);
		mv.setView("commit");
		return mv;
	}


上传的路径就是自己项目的:uploadFile文件夹下面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值