POST request with multi-page data in spring mvc

I am using ng-file-upload in Angular on the client side to send the file (image, text, etc.) to the Spring application for upload.

I have a client side running in Xampp with the url "localhost", while the Spring instance works separately with the url "localhost: 8080". Corporations on both sides are turned on, and all other requests are successfully entertained.

Client Code:

        Upload.upload({
        url: 'http://localhost:8080/file/upload',
        method:'POST',
            data: {
            uploadedPicture: file,
            uploadedFrom: 'recipe'
        },
    }).then(function(response) {
        $timeout(function() {
            $scope.result = response.data;
        });
    }, function(response) {
        if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data;
    }, function(evt) {
        $scope.progress = parseInt(100.0 * evt.loaded / evt.total);
    });

Server Side Code:

@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/file/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {
    if (!file.isEmpty()) {
        try {
            Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded " + file.getOriginalFilename() + "!");
        } catch (IOException|RuntimeException e) {
            redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
    }

    return "redirect:/";
} 

I tried cors, sending a receive request from the same code to the same resource using the get method, which is work.but, when I send an email request with data from several forms (image or any other file), it rejects the OPTIONS request.

   OPTIONS http://localhost:8080/file/upload
   XMLHttpRequest cannot load http://localhost:8080/file/upload. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.

, .

: http https, OPTIONS https://localhost:8080/file/upload net:: ERR_TIMED_OUT_ ,

?

+4
7

, :

"Access-Control-Allow-Origin"

, ?

, :

  • Access-Control-Allow-Origin: *
  • Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
  • Access-Control-Max-Age: 3600
  • Access-Control-Allow-Headers: x-request-with

, :

SimpleCORSFilter.java

 @Component
 public class SimpleCORSFilter implements Filter {

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            chain.doFilter(req, res);
        }

        public void init(FilterConfig filterConfig) {}

        public void destroy() {}

    }
+2

@CrossOrigin :

@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS}, allowedHeaders = {"Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"}, exposedHeaders = {"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"})
+1

, , , 403 . , , .

, CORS:

@RequestMapping(value="/GetSomething", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public ResponseEntity<String> getSomething() throws IOException {
    HttpHeaders responseHeaders = new HttpHeaders();
    //need for cross-domain requests
    responseHeaders.add("Access-Control-Allow-Origin", "*");
    //this one is needed, if your browser should send cookies
    responseHeaders.add("Access-Control-Allow-Credentials", "true");
    ...
    responseHeaders.setContentLength(resp.getBytes("UTF-8").length);
    return new ResponseEntity<String>(resp, responseHeaders, HttpStatus.OK);
}

EDIT:

EDIT2: , POST-? . , , , . CORS - , , !

0

, , RND , , , , .

, , , ...

            var fd = new FormData();
            fd.append('uploadedPicture', file);
            fd.append('uploadedFrom', 'recipe');

            Upload.upload({
                url: 'http://localhost:8080/file/upload',
                method: 'POST',
                data: fd,
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined},
            }).then(function (response) {
                $timeout(function () {
                    $scope.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                $scope.progress = parseInt(100.0 * evt.loaded / evt.total);
            });

, , .

0

Ajax. , . :

@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/file/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {

    String status = null;

    if (!file.isEmpty()) {
        try {
            Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
            status = "okay";

        } catch (IOException|RuntimeException e) {
            status = "error";  
        }
    } else {
        status = "error";
    }

    return "status"; // a literal string
}

, , front-end, . "", RequestParam?

, Spring MVC :

https://github.com/danialfarid/ng-file-upload/wiki/spring-mvc-example

, .

0

, . , ajax spring mvc originins = "​​/**"

0

Source: https://habr.com/ru/post/1652752/


All Articles