[英]How to temporarily create a text file without any file location and send as a response in spring boot at run time?
需要通過可用數據創建一個 txt 文件,然后需要將文件作為 rest 響應發送。 該應用程序部署在容器中。 我不想將它存儲在容器上的任何位置或 spring 引導資源中的任何位置。 有什么方法可以在運行時緩沖區創建文件而不提供任何文件位置,然后在 rest 響應中發送它? 應用程序是生產應用程序,所以我需要一個安全的解決方案
文件就是文件。 您使用了錯誤的詞-在 java 中,數據的 stream 的概念,至少對於這種工作而言,稱為InputStream
或OutputStream
。
無論你有什么方法需要一個File
? 那就是路的盡頭。 文件是一個文件。 你不能假裝它。 但是,與開發人員交談,或檢查替代方法,因為在 java 中絕對沒有理由進行數據處理需要File
。 它應該需要InputStream
或可能需要Reader
。 或者甚至可能有一種方法可以為您提供OutputStream
或Writer
。 所有這些都很好——它們是抽象,讓您可以從文件、網絡連接或整塊布料向其發送數據,這正是您想要的。
一旦你擁有其中之一,它就是微不足道的。 例如:
String text = "The Text you wanted to store in a fake file";
byte[] data = text.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream in = new ByteArrayInputStream(data);
whateverSystemYouNeedToSendThisTo.send(in);
或者例如:
String text = "The Text you wanted to store in a fake file";
byte[] data = text.getBytes(StandardCharsets.UTF_8);
try (var out = whateverSystemYouNeedToSendThisTo.getOUtputStream()) {
out.write(data);
}
看看下面的function:
進口
import com.google.common.io.Files;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.*;
import java.nio.file.Paths;
Function:
@GetMapping(value = "/getFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
private ResponseEntity<byte[]> getFile() throws IOException {
File tempDir = Files.createTempDir();
File file = Paths.get(tempDir.getAbsolutePath(), "fileName.txt").toFile();
String data = "Some data"; //
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.append(data).flush();
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] zippedData = toByteArray(new FileInputStream(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDisposition(ContentDisposition.builder("attachment").filename("file.txt").build());
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentLength(zippedData.length);
return ResponseEntity.ok().headers(httpHeaders).body(zippedData);
}
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len;
// read bytes from the input stream and store them in buffer
while ((len = in.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
return os.toByteArray();
}
簡而言之,您希望將數據存儲在 memory 中。 基本構建塊是字節數組 - byte[]
。 在 JDK 中有兩個類可以將 IO 世界與字節數組連接 - ByteArrayInputStream
和ByteArrayOutputStream
。
Rest 與處理文件時相同。
示例 1
@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
示例 2:
@GetMapping("/get-image-dynamic-type")
@ResponseBody
public ResponseEntity<InputStreamResource> getImageDynamicType(@RequestParam("jpg") boolean jpg) {
MediaType contentType = jpg ? MediaType.IMAGE_JPEG : MediaType.IMAGE_PNG;
InputStream in = jpg ?
getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg") :
getClass().getResourceAsStream("/com/baeldung/produceimage/image.png");
return ResponseEntity.ok()
.contentType(contentType)
.body(new InputStreamResource(in));
}
參考: https://www.baeldung.com/spring-controller-return-image-file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.