Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import org.springframework.http.ResponseEntity;
public class FileResponseUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileResponseUtil.class);
public static ResponseEntity<?> getFileResponse(HttpServletResponse response, File file) {
return getFileResponse(response, file, null);
}
public static ResponseEntity<?> getFileResponse(HttpServletResponse response, File file, String fileName) {
if (!file.exists()) {
LOG.error("File not found: " + file.getAbsolutePath());
return new ResponseEntity<>("File " + file.getName() + " not found", NOT_FOUND);
}
if (!file.canRead()) {
LOG.error("File not readable: " + file.getAbsolutePath());
return new ResponseEntity<>("File " + file.getName() + " is not readable", INTERNAL_SERVER_ERROR);
}
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName == null ? file.getName() : fileName, StandardCharsets.UTF_8));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setCharacterEncoding("UTF-8");
byte[] bytes = new byte[1024];
try ( OutputStream out = response.getOutputStream(); InputStream is = new FileInputStream(file)) {
int read;
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return null;
}
}