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

Example – Spring Boot file upload AJAX – Fine Uploader

Fine Uploader plug in used in this example is available at FINEUPLOADER

 

1. Using FINEUPLOADER JS

 

<html>
  <head>
      <link href="<%=request.getContextPath()%>/js/all.fine-uploader/fine-uploader-new.css" rel="stylesheet" type="text/css"/>
  </head>
  <body>

    <!-- The element where Fine Uploader will exist. -->
    <div id="fine-uploader">
    </div>

    <!-- Fine Uploader -->
    <script src="<%=request.getContextPath()%>/js/all.fine-uploader/all.fine-uploader.js" type="text/javascript"></script>

    <script type="text/template" id="qq-template">
        <div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
            <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
                <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
            </div>
            <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                <span class="qq-upload-drop-area-text-selector"></span>
            </div>
            <div class="qq-upload-button-selector qq-upload-button">
                <div>Upload a file</div>
            </div>
            <span class="qq-drop-processing-selector qq-drop-processing">
                <span>Processing dropped files...</span>
                <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
            </span>
            <ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
                <li>
                    <div class="qq-progress-bar-container-selector">
                        <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
                    </div>
                    <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                    <img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
                    <span class="qq-upload-file-selector qq-upload-file"></span>
                    <span class="qq-edit-filename-icon-selector qq-edit-filename-icon" aria-label="Edit filename"></span>
                    <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                    <span class="qq-upload-size-selector qq-upload-size"></span>
                    <button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
                    <button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
                    <button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>
                    <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
                </li>
            </ul>

            <dialog class="qq-alert-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Close</button>
                </div>
            </dialog>

            <dialog class="qq-confirm-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">No</button>
                    <button type="button" class="qq-ok-button-selector">Yes</button>
                </div>
            </dialog>

            <dialog class="qq-prompt-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <input type="text">
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Cancel</button>
                    <button type="button" class="qq-ok-button-selector">Ok</button>
                </div>
            </dialog>
        </div>
    </script>

    <script>
        var uploader = new qq.FineUploader({
            debug: true,
            element: document.getElementById('fine-uploader'),
            request: {
            	inputName: 'file',
                endpoint: '/upload'
            },
            deleteFile: {
                enabled: true,
                endpoint: '/upload'
            },
            retry: {
               enableAuto: true
            }
        });
    </script>
  </body>
</html>

Fine uploader also provides facility to delete uploaded file. I have implemented @RequestMapping(value = “/upload/{qquuid}”, method = { RequestMethod.DELETE }) to support delete

2. Spring Boot Upload Controller

 

package com.example.springapp;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
	private static String UPLOADED_FOLDER = "e:/files/";

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

	// implemented only for Fine Uploader
	@RequestMapping(value = "/upload/{qquuid}",
	        method = { RequestMethod.DELETE })
	public @ResponseBody Object uploadDelete(
	        HttpServletRequest request,
	        @PathVariable("qquuid") String qquuid) {
		System.out.println("uploadDelete() called");
		String fileName = (String) request.getSession()
		        .getAttribute(qquuid);
		try {
			if (fileName != null) {
				Path path = Paths
				        .get(UPLOADED_FOLDER + fileName);
				Files.delete(path);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return getSuccessMessage().toString();
	}

	@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 {
			// for Fine Uploader delete functionality
			String qquuid = request.getParameter("qquuid");
			System.out.println("qquuid=" + qquuid);
			if (qquuid != null) {
				request.getSession().setAttribute(qquuid,
				        file.getOriginalFilename());
			}
			// for Fine Uploader delete functionality ends

			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();
	}
//--------------------------
}

Tags: ,

by , on February 10th, 2017

  • Categories