柳絮飞祭奠 阅读(578) 评论(0)
引入jar包:jersey-media-multipart-2.22.jar
前端:
<body>
	<input id="commonFile" type="file" class="commonFile"
		onchange='angular.element(this).scope().commonFileChanged(this)'
		multiple="multiple" />
	<br>
</body>
<script type="text/javascript">
	angular.module("uploadApp", []).controller("uploadCtrl",
			function($scope, $http) {
				$scope.commonFileChanged = function() {
					var $$fd = new FormData();
					var _file = document.getElementById("commonFile");
					$$fd.append('file', _file.files[0]);
					$http({
						method : 'post',
						data : $$fd,
						//拼装uri路径参数
						url : "/Jersey/api/1.0/my/upload",
						headers : {
							'Content-Type' : undefined
						},
						/*序列化 formdata object*/
						transformRequest : angular.identity
					}).success(function(data) {
						alert(angular.toJson(data));
					});
				};
			});
	angular.bootstrap(document, [ 'uploadApp' ]);
</script>


后端:
@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Path("/upload")
	@Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" })
	public String upload(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition disposition) {
		String nFileName = disposition.getFileName();
		File file = new File("D:\\file\\" + nFileName);
		try {
			// 使用common io的文件写入操作
			FileUtils.copyInputStreamToFile(fileInputStream, file);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return "{\"success\",\"true\"}";
	}