Javascript 使用二进制数据通过AJAX从jsPDF上传PDF
我正在尝试将使用jsPDF在前端javascript上生成的PDF传递给Spring Framework MVC后端。下面是我编写的前端代码:Javascript 使用二进制数据通过AJAX从jsPDF上传PDF,javascript,java,jquery,ajax,spring,Javascript,Java,Jquery,Ajax,Spring,我正在尝试将使用jsPDF在前端javascript上生成的PDF传递给Spring Framework MVC后端。下面是我编写的前端代码: var filename=“thefile”; var constructURL='/daas rest services/dashboard/pdfPrintUpload/'+filename; var url=restService.getUrl(constructURL); var fileBytes=btoa(pdf.output()); $ht
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(函数(数据){
控制台日志(数据);
})
.错误(函数(e,a){
控制台日志(e);
控制台日志(a);
});
pdf变量已正确生成,在调用pdf.save(“文件名”)时可以确认是否正确打开。下面是在Spring MVC后端为该调用编写的Java代码:
@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;
}
每次我提出请求,都会收到400个错误,告诉我:
错误400:所需字节[]参数“fileBytes”不存在
我可以在请求负载中确认正在传输大量数据,但是后端似乎不希望接受该参数
这样做的目的是,我希望能够从pdf中获取数据,然后在后端对其进行解码,以便以后可以将pdf发布到服务器上的某个位置。我的代码中是否缺少一些东西,导致这些请求不断失败,是否有更简单、更有效的方法来实现此功能?尝试使用ng文件上载。链接和示例可在链接上找到 对于服务器端代码,请尝试使用此
@RequestMapping(value = "/pdfPrintUpload")
@ResponseBody
public void postPrintDocument(@RequestParam("file") MultipartFile file) {
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(/*path to save file*/);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案是将@RequestParam更改为@RequestBody@RequestParam是在路径中发送的参数。