Ajax SpringMVC 上传文件

前端之家收集整理的这篇文章主要介绍了Ajax SpringMVC 上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

jsp 文件

	<form id="uploadForm" method="post" name="fileinfo"
		enctype="multipart/form-data">
		<input type="file" id="image" name="image"> <input
			type="button" class="btn btn-default" onclick="upload()" value="上传图片">
	</form>

Ajax写法
	function upload() {
		var uploadResult = document.getElementById("upload-result");
		uploadResult.style.color = "green";
		uploadResult.innerHTML = "正在上传.....";
		var formData = new FormData($("uploadForm")[0]);
		formData.append('Content-Type','multipart/form-data');
		formData.append('image',$('input[type=file]')[0].files[0]);
		$.ajax({
			url : "${pageContext.request.contextPath}/api/v1/file",type : 'POST',data : formData,dataType : 'json',contentType : false,processData : false,cache : false,//防止缓存
			error : function(data) {
				alert("请求失败,网络异常")
				console.log(data);
			},success : function(data) {
				console.log(data);
				var code = data.status;
				if (code == 200) {
					uploadResult.style.color = "green";
					uploadResult.innerHTML = "上传成功";
					imgUrl = data.data;
				} else {
					uploadResult.style.color = "red";
					uploadResult.innerHTML = "上传失败";
				}
			}

		});
	}


SpringMVC服务器端写法:

@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Object uploadFile(HttpServletRequest request) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据,
		String fileUrl = "";
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					try {
						GridFSInputFile inputFile = fileService.save(file.getInputStream(),file.getOriginalFilename());
						if (inputFile == null) {
							return StatusConfig.FileUploadError;
						} else {
							fileUrl = inputFile.getId().toString();
							System.out.println("fileUrll" + (fileUrl));
						}
					} catch (IllegalStateException | IOException e) {
						return StatusConfig.FileUploadError;
					}
				}
			}
			HashMap<String,Object> hashMap = new HashMap<String,Object>();
			fileUrl = this.getHttpFilePath() + fileUrl;
			hashMap.put(ConstantsKey.STATUS,200);
			hashMap.put(ConstantsKey.DATA,fileUrl);
			String json = ConvertUtils.as().toJson(hashMap);
			System.out.println("photourl:" + json);
			return json;
		} else {
			return StatusConfig.RequestTypeError;
		}
	}
原文链接:https://www.f2er.com/springmvc/162062.html

猜你在找的SpringMVC相关文章