SpringMVC(四)上传文件、json数据交互

上传文件

* tomcat中配置虚拟目录

修改server.xml,在里面添加

<Context docBase="D:\develop\upload\temp" path="/pic" reloadable="false"/>

这样,就可以通过访问http://localhost:8080/pic访问到d盘下的文件    

eclipse中设置


依赖jar


SpringMVC.xml中配置文件上传解析器

<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 设置文件上传大小 单位B 50M-->
	<property name="maxUploadSize" value="52428800" />
</bean>

jsp页面修改

<form action="${pageContext.request.contextPath}/item/fileUpload.action"
		method="post" enctype="multipart/form-data">
		<input type="file" name="file"> <input type="submit"
			value="提交">
	</form>

enctype 必须改为 multipart/form-data

controller方法

@RequestMapping("/fileUpload.action")
	public String doFileUpload(@RequestParam(required = false) MultipartFile file,
			HttpServletRequest request
			) throws IllegalStateException, IOException{
		if(file==null){
			return "itemList";
		}
		String orginFileName = file.getOriginalFilename();
		String fileName = UUID.randomUUID()+""+orginFileName.substring(orginFileName.lastIndexOf("."));
		String path = request.getServletContext().getRealPath(File.separatorChar+"WEB-INF"+File.separatorChar+"upload");
		File file2 = new File(path, fileName);
		if(!file2.getParentFile().exists()){
			file2.getParentFile().mkdirs();
		}
		file.transferTo(file2);
		return "forward:/itemList.action";
	}

文件路径访问不到的异常

因为父目录不存在,加上file.getParentFile().mkdirs()创建父目录解决

存放文件的路径说明

1. 直接在webRoot下创建upload文件夹,上传文件放在这里,在浏览器上能够直接访问到,因此这里存放是安全的

http://localhost:8081/goldSpringDemo/upload/0ea8aa64-76c6-49bf-9ecd-3a56c9fa87ed.xls

2. 在webRoot下的WEB-INF下创建upload文件夹,将上传文件放在这里,浏览器无法直接访问到,这里比较安全

,本例中用的就是这种

多文件上传

修改jsp页面

<form action="${pageContext.request.contextPath}/item/fileUploads.action"
		method="post" enctype="multipart/form-data">
		<input type="file" name="files"> 
		<input type="file" name="files"> 
		<input type="file" name="files"> 
		<input type="submit" value="提交">
	</form>

修改controller方法形参,遍历后按照单个文件的处理流程处理就是

@RequestMapping("/fileUploads.action")
	public String doFileUploads(@RequestParam(required = false) List<MultipartFile> files,
			HttpServletRequest request
			) throws IllegalStateException, IOException{
		if(files==null){
			return "itemList";
		}
		for(int i = 0;i<files.size();i++){
			MultipartFile file = files.get(i);
			String orginFileName = file.getOriginalFilename();
			String fileName = UUID.randomUUID()+""+orginFileName.substring(orginFileName.lastIndexOf("."));
			String path = request.getServletContext().getRealPath(File.separatorChar+"WEB-INF"+File.separatorChar+"upload");
			File file2 = new File(path, fileName);
			if(!file2.getParentFile().exists()){
				file2.getParentFile().mkdirs();
			}
			file.transferTo(file2);
		}
		return "forward:/item/itemList.action";
	}

Json数据交互

@RequestBody注解将请求的json数据转为java对象进行绑定

@ResponseBody将controller方法返回的java对象转为json响应客户端。

jar支持


JSON转换器

如果xml中使用注解驱动<mvc:annotation-driven/>,不需要配置json转换器,不适用注解驱动就需要配置

<!--处理器适配器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
		<list>
		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
		</list>
		</property>
	</bean>

开始测试下:

jsp页面:

<script type="text/javascript">	
	//live 能够对还没有添加进DOM的元素有效,jquery 1.7后使用on替换
		$("#bt").live("click",function(){
			$.ajax({
				type:'GET',
				url:contentpath+'/item/json.action',
				data:$("#form1").serialize(),
				contentType:"application/x-www-form-urlencoded;charset=utf-8",
				dataType:'json',
				success:function(data){
					console.log(data);
				},
				error:function(){
					alert('服务器连接失败,请重试!');
				}
				
			});		
		});
	</script>
	<form action="" id="form1">
	<table>
		<tr>
			<td>编号</td>
			<td>
				<input type="text" name="item.id">
			</td>
		</tr>
		<tr>
			<td>名称</td>
			<td>
				<input type="text" name="item.name">
			</td>
		</tr>
		<tr>
			<td>时间</td>
			<td>
				<input type="text" name="item.time">
			</td>
		</tr>
		<tr>
			<td>备注</td>
			<td>
				<input type="text" name="item.remark">
			</td>
		</tr>
		<tr>
			<td>
				<input id="bt" type="button" value="ajax提交">
			</td>
		</tr>
	</table>
	</form>

controller方法

@RequestMapping("/json.action")
	public @ResponseBody Item dojsonSupport(QueryVo qv){
		return qv.getItem();
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值