Uploading PDF from jsPDF with AJAX using binary data

时间:2015-09-01 21:35:12

标签: javascript java jquery ajax spring

I am attempting to pass a PDF I have generated on frontend javascript using jsPDF to a Spring Framework MVC backend. Below is the front end code I have written:

var filename = "thefile";
var constructURL = '/daas-rest-services/dashboard/pdfPrintUpload/' + filename;
var url = restService.getUrl(constructURL);
var fileBytes = btoa(pdf.output());
$http.post(url, fileBytes).success(function(data) {
    console.log(data);
  })
  .error(function(e, a) {
    console.log(e);
    console.log(a);

  });

The pdf variable has been generated properly and can confirm is opens correctly when calling pdf.save("filename"). Below is the Java code which has been written on the Spring MVC backend for this call:

@RequestMapping(method = RequestMethod.POST, value = "/pdfPrintUpload/{documentName}")
public @ResponseBody String postPrintDocument(@PathVariable String documentName, @RequestParam byte[] fileBytes) {
    String methodName = "postPrintDocument";
    if(logger.isLoggable(Level.FINER)){
        logger.entering(CLASS_NAME, methodName);               
    }
    String check;
    if(fileBytes != null){
        check = "not null";
    } else {
        check = "null ";
    }
    //Decoding the bytestream
    //Save to file location
    //return file location
    String returnValue = "HI " + documentName + "  " + check;
    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(CLASS_NAME, methodName);
    }
    return returnValue;
}

Each time I make a request, I am getting 400 Errors telling me:

Error 400: Required byte[] parameter 'fileBytes' is not present

I can confirm in the request payload that a large amount of data is being transmitted, however the backend does not seem to want to accept the parameter.

The purpose of doing this is that I want to be able to get the data from the pdf and then decode it on the backend so I can later publish the pdf to a location on the server. Is there something I am missing in my code for these requests to keep failing, and is there an easier more efficient way to achieve this functionality?

2 个答案:

答案 0 :(得分:4)

解决方案是将@RequestParam更改为@RequestBody。 @RequestParam是在路径中发送的参数。 @RequestParam vs @PathVariable

答案 1 :(得分:3)

尝试使用ng-file-upload。链接和示例可在链接

上找到

ng-file-upload

用于服务器端代码尝试使用此

$ git push
To git@git.example.com:your/repository.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@git.example.com:your/repository.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.