从 ajax 绑定 Blob 类型

Binding Blob type from ajax

提问人:wnotunas 提问时间:8/10/2023 最后编辑:wnotunas 更新时间:8/10/2023 访问量:64

问:

我开发了一个 API,用于验证 Excel 文件并显示其中的代码内容。我的目标是在客户端使用 Ajax 调用此 API。但是,我遇到了 blob 类型 xhrcontent 的问题,这似乎引起了混淆。为了帮助澄清,我提供了相关代码片段的概述:

  • 这是 API
@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
$.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,我确信该文件有 err (count >0) 的响应(打开成功并显示我想要的内容)并且文件没有 err 平均响应 (count==0) 已经是预期的结果。任何支持对我来说都是有价值的,感谢您的时间和帮助!

  • 我尝试在 Ajax 请求设置中添加此选项,然后文件运行良好,但是当变量没有错误( mean count == 0 )时,将数据传输到弹出窗口的响应不起作用,并且 Ajax 在 之后抛出 inside 的错误情况是countResponseDtoresponseTextconsole.log(error)[object Blob]

    xhrFields: {
       responseType: 'blob'
    }, 
    
  • 然后使用上面的相同选项,我尝试在成功区域内添加它,但它似乎毫无意义xhr.responseType = '';response.isOk == true

Java Ajax Spring XMLhttpRequest blob

评论


答: 暂无答案