gpt4 book ai didi

java - 如何使用 JAVA EE 获取用于下载文件的 HttpServletResponse 实例

转载 作者:行者123 更新时间:2023-12-02 01:55:13 24 4
gpt4 key购买 nike

我在服务器上有一个txt文件(之前生成的)。当用户单击按钮时,它会生成文件,现在我想(另外)在我的函数中下载该文件。但我无法让它工作(我是 JAVA EE 的新手),因为我不知道如何获取 HttpServletResponse。

从网络上我用这个调用函数:

@Path("getreport")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getreport(CommonInput input) {
JSONObject j = objectmapper.conertValue(reportBean.getreport(),JSONObject.class);
return j;
}

reprotBean有功能:

public void getreport() {
//...doing many things
//generating my file
List<String> lines = new ArrayList<>();
lines.add("star file");
//..adding many lines
Path file = Paths.get("C:\\Users\\myuser\\file.txt");
Files.write(file, lines, StandardCharsets.UTF_8);

downloadFile();
//...doing many things
}

我找到了下载文件的方法:

public void downloadFile(HttpServletResponse response){ 
String sourceFile = ""C:\\Users\\myuser\\file.txt"";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.txt";
response.setContentType("text/txt");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));

} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}

private long stream(InputStream input, OutputStream output) throws IOException {

try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;

while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}

当我尝试使用 downloadFile() 时,它需要 HttpServletResponse,而我没有该参数。我不明白如何获得它(它是如何工作的),或者我是否必须使用其他方法来下载我的文件?

我发现的所有解决方案都需要 HttpServletResponse (从浏览器下载文件)

最佳答案

如果您已经生成了该文件。只需将其写入 HttpServletResponse

        resp.setContentType("text/plain");
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");

try(InputStream in = req.getServletContext().getResourceAsStream("sample.txt");
OutputStream out = resp.getOutputStream()) {

byte[] buffer = new byte[ARBITARY_SIZE];

int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}

确保您的文件可以被 ServeletContext 访问

如果您使用 Spring Rest 框架。可以引用下面

    @GetMapping("/download")
public ResponseEntity<byte[]> downloadErrorData() throws Exception {
List<Employee> employees = employeeService.getEmployees();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(employees);
byte[] isr = json.getBytes();
String fileName = "employees.json";
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}

信用至:https://www.jeejava.com/file-download-example-using-spring-rest-controller/

关于java - 如何使用 JAVA EE 获取用于下载文件的 HttpServletResponse 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57401833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com