欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Jersey RESTful WebService框架学习(七)文件上传

程序员文章站 2022-03-10 23:13:32
...
引入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\"}";
	}
相关标签: java REST Jersey