我开发了一个 API,用于验证 Excel 文件并显示其中的代码内容。我的目标是在客户端使用 Ajax 调用此 API。但是,我遇到了
blob
类型 xhrcontent
的问题,这似乎引起了混乱。为了帮助澄清,我提供了相关代码片段的概述:
@PostMapping("/valid-excel")
public ResponseEntity<Object> validateExcel(@RequestParam("file") MultipartFile file) {
try (InputStream is = file.getInputStream()) {
/* code handle read and write excel file etc..
* inside a count variable for counting error
* if count > 0 mean error exist and give out file for client can download
* else if count == 0 mean notifying client that their file good has no err
* if the system has interval error, fire swal popup for them
*/
if (count != 0) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String fileName = "IMPORT_FILE_" + file.getName() + "_validate.xlsx";
headers.setContentDispositionFormData(fileName, fileName);
return ResponseEntity.ok().headers(headers).body(outputStream.toByteArray());
} else {
return ResponseEntity.ok().body(new ResponseDto(true, Message.SUCCESS_VALID_EXCEL.value()));
}
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new ResponseDto(false, Message.ERROR_INTERVAL_SERVER.value()));
}
}
$.ajax({
url: '/valid-excel',
type: 'POST',
data: file,
processData: false,
contentType: false,
success: function (response) {
if (response.status != true || response.status == undefined ){
var url = window.URL.createObjectURL(data);
var blob = new Blob([response.body], { type: 'application/octet-stream' });
var downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = 'VALIDATED_EXCEL_FILE.xlsx';
downloadLink.textContent = 'Download Validated Excel File';
$('#fileInput').after(downloadLink);
} else {
Swal.fire({
icon: 'success',
title: 'Success',
text: response.data,
});
}
},
error: function (error) {
console.log({error})
Swal.fire({
icon: 'error',
title: 'Error',
text: 'An error occurred while processing the file.',
});
}
});
虽然此方法有效,但文件无法正常运行。尝试打开文件时,显示错误消息:
"Excel cannot open the file because the format is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
我怀疑该错误可能是在使用
blob
方法将字节流转换为文件期间发生的。
任何人都可以帮我解决 Ajax 端 Blob 类型的问题吗?我在 Postman 上测试了我的 API,我确信该文件有响应错误(计数 >0)(打开成功并显示我想要的内容)并且文件没有错误意味着响应(count==0)已经是预期的结果。任何支持对我来说都很有价值,感谢您的时间和帮助!
我尝试在Ajax请求设置上添加此选项,然后文件运行良好,但是当变量
count
没有错误(平均计数== 0)时,将数据传输到弹出窗口的响应ResponseDto
不会工作并且 Ajax 在 responseText
是 console.log(error)
之后抛出
[object Blob]
的错误情况
xhrFields: {
responseType: 'blob'
},
然后使用上面相同的选项,我尝试在成功区域内添加此
xhr.responseType = '';
if response.isOk == true
,但这似乎毫无意义
我和你在同一页面上,伙计。甚至不仅仅是简单的代码,而且还得到了错误的数据类型。 希望有人能帮我摆脱困境。