[英]How to download a file as a blob/byte in Java/Spring
我有一個 Spring Boot 應用程序,它允許用戶上傳文件(例如 .doc 或 jpegs)並將它們保存到 H2 數據庫。 雖然我能夠從數據庫中保存和檢索文件,並將數據保存為一個字節,但我無法允許用戶將文件下載到他們的機器上。
我在網上找到的現有解決方案,例如這個
要么不考慮將 Blob 保存為字節,要么涉及復雜的 sql 查詢,這些查詢似乎不適合我的應用程序或 controller 操作的上下文。
從 H2 數據庫中檢索 blob 后,如何將 blob 下載到用戶的計算機?
我當前的 controller 動作是從一個 href 觸發的:
@GetMapping("/download")
public String downloadFile() {
List<Files> files = fileMapper.getFiles();
Files newFile = files.get(0);
byte[] downloadedFile = newFile.getFileData();
return "home";
}
我在這里也有我的回購:
您可以從org.springframework.core.io.Resource
導入Resource
並從您的文件中創建InputStreamResource
,應如下所示:
public ResponseEntity<Resource> downloadFile() {
byte[] bytes = yourMethodToGetByteBlobFromDB(....);
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bytes));
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Disposition", String.format("attachment; filename=your_file_name"));
return ResponseEntity.ok()
.headers(headers)
.contentLength(bytes.length)
.contentType("application/octet-stream")
.body(resource);
}
下面的代碼非常適合我。
下載服務中的邏輯 class
public ResponseEntity<Resource> downloadFile(String fileId) throws Exception
{
try
{
DBFile dbFile = dbFileStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(dbFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
.body(new ByteArrayResource(dbFile.getData()));
}
catch(Exception e)
{
throw new Exception("Error downloading file");
}
}
數據庫文件存儲服務
public DBFile getFile(String fileId) throws Exception {
return dbFileRepository.findById(fileId)
.orElseThrow(() -> new Exception("File not found with id " + fileId));
}
數據庫文件回購
@Repository
public interface DBFileRepository extends JpaRepository<DBFile, String> {
}
DB 文件的實體 Class
@Entity
@Table(name = "files")
public class DBFile {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
private String fileName;
private String fileType;
@Lob
private byte[] data;
//getter and setter
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.