Posted In: File Upload, Java Script, Spring, Spring Boot

Example – Spring Boot file upload AJAX – Dropzone

Dropzone plug in used in this example is available at DROPZONE JS

 

 

1. Using DROPZONE JS

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File Upload</title>
<script src="<%=request.getContextPath()%>/js/jquery-3.1.1.js"
	type="text/javascript"></script>
<script
	src="<%=request.getContextPath()%>/js/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script
	src="<%=request.getContextPath()%>/js/dropzone-4.3.0/dist/dropzone.js"></script>


<link rel="stylesheet"
	href="<%=request.getContextPath()%>/js/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet"
	href="<%=request.getContextPath()%>/js/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">
<link rel="stylesheet"
	href="<%=request.getContextPath()%>/js/dropzone-4.3.0/dist/dropzone.css">

</head>
<body>
	<div class="container-fluid">
		<div class="panel panel-default" id="fileupload_main_panel">
			<div class="panel-body">
				<div class="row">
					<div class="col-md-12">
						<form enctype="multipart/form-data"
							action="<%=request.getContextPath()%>/upload" method="POST"
							class="dropzone" id="fileUploadForm">

							<span id="fileUploadStatus"> </span>

						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

 

2. Spring Boot Upload Controller

	@RequestMapping(value = "/upload",
	        method = { RequestMethod.POST })
	public @ResponseBody Object upload(
	        @RequestParam("file") MultipartFile file,
	        HttpServletRequest request) {
		System.out.println("upload() called");

		if (file.isEmpty()) {
			request.setAttribute("message",
			        "Please select a file to upload");
			return "uploadStatus";
		}

		try {
			byte[] bytes = file.getBytes();
			Path path = Paths.get(UPLOADED_FOLDER
			        + file.getOriginalFilename());
			Files.write(path, bytes);

			request.setAttribute("message",
			        "You have successfully uploaded '"
			                + file.getOriginalFilename() + "'");

		} catch (IOException e) {
			e.printStackTrace();
		}

		return getSuccessMessage().toString();
	}

	private JSONObject getSuccessMessage() {
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject("{\"success\":true}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

 

Tags: ,

by , on February 10th, 2017

  • Categories