1. 程式人生 > >springMVC+jersey實現跨伺服器檔案上傳

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" onchange="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;
	}