2

I'm trying to upload a file that have a progress bar.

var fileInput = document.getElementById('jquery-ajax-single')
    var form = new FormData();
    form.append('uploadFile',fileInput.files[0]);

    $.ajax({
        url: "file/upload",
        processData : false,
        contentType : false,
        data : form,
        type : 'POST',
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
                console.log(Math.floor(e.loaded / e.total *100) + '%');
                $('#progress-jquery-ajax-single.progress-bar-progress').css(
                        'width', Math.floor(e.loaded / e.total * 400)+ 'px'
                );
            };
           return xhr;
        }
    });

Code above is working and is able to go to FileController

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
    public void upload(@RequestParam MultipartFile uploadFile){


        System.out.println("name : " + uploadFile.getOriginalFilename());
        System.out.println("content-type : " + uploadFile.getContentType());
        System.out.println("size : " + uploadFile.getSize());
    }
}

Every time I process the ajax it shows the progress of the upload, after reaching 100% goes to the FileController and prints the input file information, but upon looking at chrome browser console it returns :

jquery-2.1.4.js:8630 POST http://localhost:8080/FileUploadWeb/file/upload 404 (Not Found).

I also tried to use dropzone.js and it also returns error 404 but the url became http://localhost:8080/FileUploadWeb/file/file/upload

<form id="my-dropzone"action="file/upload" class="dropzone"></form>

1 Answers1

0

After stumbling across this, the trick that should work was to return a ResponseBody entity in the POST method:

@PostMapping(value = "/upload")
public ResponseEntity<String> upload(@RequestParam MultipartFile uploadFile) {
    System.out.println("name : " + uploadFile.getOriginalFilename());
    System.out.println("content-type : " + uploadFile.getContentType());
    System.out.println("size : " + uploadFile.getSize());

    return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56