首页 > 解决方案 > 下载的文件在 react-Js 中损坏,它从 Spring Boot 获取数据

问题描述

以下是我的托管实体

@Entity @Table(name = "主机")

公共类托管{

@Id
private String uid;

// ********* for files ********

@Transient
private MultipartFile aadharFile;
private String aadharFileName;
private String aadharFileType;
@Lob
private byte[] aadharFileData;

}

以下是我的后端服务

    @GetMapping("/hostings/downloadIdProof/{uid}")
    public ResponseEntity<byte[]> downloadIdProof (@PathVariable String uid) {
    
    Hosting hosting = service.findById(uid).get();
    
    HttpHeaders header = new HttpHeaders();
            
    header.setContentType(MediaType.valueOf(hosting.getAadharFileType()));
    header.setContentLength(hosting.getAadharFileData().length);
    header.set("Content-Disposition", "attachment; filename=" + hosting.getAadharFileName());
    
    return new ResponseEntity<>(hosting.getAadharFileData(), header, HttpStatus.OK);
}

以下是我的反应代码

    const downloadFile = (file) => {
    hostingApi.get(`/hostings/downloadIdProof/${user.uid}`)
    .then(response=>{

        console.log(response)

        var filename =  response.headers["content-disposition"].split("filename=")[1];
        
        let url=  window.URL.createObjectURL(new Blob([response.data], {'type': `${response.headers["content-type"]}`}));
        
        let a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        
    })
    .catch(err=>{
        console.log(err);
    })
}

此处文件已下载但已损坏“看来我们不支持此文件格式”另外这是“response.data”的格式���� JFIF

标签: reactjsspring-boot

解决方案


推荐阅读