REST使用Spring Boot / JPA,Postgres上传/下载大文件

问题描述

我正在尝试上传约700MB的文件,并在春季启动时通过REST API以Postgres作为数据库下载该文件。我知道Postgres并不是要走的路,但我仍然想按原样解决它。

我在运行时向VM添加-Xmx2024m后,REST上传工作正常。 调用uploadobjectEntityRepository.findById(id)时,REST下载出现错误

Caused by: org.postgresql.util.PsqlException: ERROR: invalid memory alloc request size 1381847031

错误将表示数据已损坏,但是上载服务干净结束。在Postgres日志中上传期间也没有错误。在数据库中,字段data的类型为bytea

可能是什么问题?

缩写代码

@Entity
@Table(name = "UploadobjectEntity")
public class UploadobjectEntity implements Serializable {
    ...
    @Lob
    @Column(name = "data",nullable = false)
    private byte[] data;
    ...
}

@PostMapping("/upload")
public ResponseEntity<Uploadobject> upload(@RequestPart multipartfile file){
    ...
    Uploadobject o = customService.saveUploadobject(file);
    ...
}

@RequestMapping(value = "/download/{id}",method = RequestMethod.GET)
public void getByteArray(@PathVariable("id") Long id,HttpServletResponse response) {
    Uploadobject uploadobject = customService.load(id);
    ByteSource byteSource = ByteSource.wrap(uploadobject.getData());

    InputStream stream = byteSource.openStream();

    response.setContentType(...);
    response.setContentLength(...);
    IoUtils.copy(stream,response.getoutputStream());
}

//Custom Service
public Uploadobject saveUploadobject(multipartfile file) {
    ...
    UploadobjectEntity uploadobjectEntity = new UploadobjectEntity();
    uploadobjectEntity.setData(file.getBytes());
    ...
    uploadobjectEntity = uploadobjectEntityRepository.save(uploadobjectEntity);

    return uploadobjectEntityMapper.toDto(uploadobjectEntity);
}

public Uploadobject load(Long id) {
    return uploadobjectEntityRepository.findById(id).map(uploadobjectEntityMapper::toDto);
}   

解决方法

添加您的代码application.properties

spring.http.multipart.max-file-size=1000MB
spring.http.multipart.max-request-size=1000MB