如何临时创建一个没有任何文件位置的文本文件,并在运行时的spring boot中作为响应发送?

igsr9ssn  于 2022-11-29  发布在  Spring
关注(0)|答案(4)|浏览(133)

需要通过可用数据创建一个txt文件,然后需要将该文件作为rest响应发送。应用程序部署在container中。我不想将其存储在container上的任何位置或spring boot资源中的任何位置。有没有什么方法可以在运行时缓冲区创建文件,而不提供任何文件位置,然后在rest响应中发送它?应用程序是生产应用程序,所以我需要一个安全的解决方案

bejyjqdl

bejyjqdl1#

文件就是文件,你用错词了--在java中,数据流的概念,至少对于这类工作,被称为InputStreamOutputStream
不管你有什么方法,只要它接受一个File就行了。一个文件就是一个文件。你不能伪造它。但是,和开发人员谈谈,或者检查一下替代方法,因为在java中,数据处理完全没有理由需要一个File,它应该需要一个InputStream,或者可能需要一个Reader。或者甚至有一个方法可以给你一个OutputStreamWriter。所有这些东西都很好--它们是抽象的,让你只向它发送数据,从一个文件,一个网络连接,或者组成一个整体,这是你想要的。
一旦你有了这样的一个,它就变得微不足道了。例如:

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);
}
m1m5dgzv

m1m5dgzv2#

看看下面的函数:

进口

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;

功能:

@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();
    }
8i9zcol2

8i9zcol23#

简单地说,你想把数据存储在内存中。基本的构建块是字节数组-byte[]。在JDK中有两个类将IO世界与字节数组连接起来-ByteArrayInputStreamByteArrayOutputStream
其余的都是一样的,当处理文件。

euoag5mw

euoag5mw4#

实施例一

@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {

InputStream in = getClass()
  .getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}

例二:

@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

相关问题