springMVC+jersey实现跨服务器文件上传

1.首先添加所需要的jar包

   

 


2.在springMVC的配置文件中添加文件上传解析器



  <!-- 文件上传的解析器 -->
	 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	 	<!-- 文件上传大小的限制 -->
	 	<property name="maxUploadSize" value="5000000"></property>
	 	<property name="defaultEncoding" value="UTF-8"></property>
	 </bean>


3.jsp页面


<form id="fm" action="" method="post">
	<p>
		<img src="" alt="" id="imgSrc"/>
		请上传头像:<input type="file" name="imgFile" id="imgFile" οnchange="fileUpload();"/>
		<input type="hidden" id="reletivePath" name="reletivePath" value="">
	</p>
</form>


4.文件上传的 js


<!-- 文件上传js -->
<script type="text/javascript">
		function fileUpload(){
			var option = {
				type:"POST",
				url:"${pageContext.request.contextPath }/user/fileUpload.do",
				data:{
					fileName:"imgFile"
				},
				success:function(reData){
					alert(reData.reletivePath);
					$("#imgSrc").attr("height",100);
					$("#imgSrc").attr("width",100);
					$("#imgSrc").attr("src",reData.fullPath);
					$("#reletivePath").val(reData.reletivePath);
				},
				dataType:"json"
			};
			$("#fm").ajaxSubmit(option);
		}
</script>


5. controller


    /*
	 * 文件上传
	 */
	@RequestMapping("fileUpload")
	public @ResponseBody Map<String , String> fileUpload(HttpServletRequest request,String fileName){
		System.out.println(111);
		//1.将普通请求转换为多部件请求
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest)request;
		//2.根据文件名获取文件对象
		CommonsMultipartFile mf = (CommonsMultipartFile)mr.getFile(fileName);
		//3.获取文件全名称
		String originalFilename = mf.getOriginalFilename();
		System.out.println("文件全名称"+originalFilename);
		//4.获取后缀
		String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
		System.out.println("后缀"+suffix);
		//5.将文件对象转换为字节
		byte[] fileBytes = mf.getBytes();
		//6.获取新的随机文件名
		String newFileName="";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		int num = (int)(Math.random()*899)+100;
		newFileName = sdf.format(new Date())+num;
		
		System.out.println("新的随机文件名"+newFileName);
	//开始上传
		//1.创建jesy服务器
		Client client = Client.create();
		String fullPath = "http://localhost:8088/fileServiceProject/upload/"+newFileName+suffix;
		//把文件关联到远程服务器
		WebResource wr = client.resource(fullPath);
		//2.相对路径
		String reletivePath = "/upload/"+newFileName+suffix;
		//3.上传
		wr.put(String.class, fileBytes);
		Map<String , String> map = new HashMap<String, String>();
		map.put("fullPath", fullPath);
		map.put("reletivePath", reletivePath);
		return map;
	}





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值