package ch.std.fileservice.rest;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/rest/file")
public class GenericFileService {
public GenericFileService() {
super();
}
@GetMapping
public void get(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
String path = httpServletRequest.getParameter("path");
if (path == null) {
httpServletResponse.setContentType("text/html; charset=UTF-8");
httpServletResponse.getWriter().print("path is missing");
return;
}
String mimeType = URLConnection.guessContentTypeFromName(path);
if (mimeType == null) {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
mimeType = mimeTypesMap.getContentType(path);
}
httpServletResponse.setContentType(mimeType);
httpServletResponse.setHeader("Transfer-Encoding", "chunked");
OutputStream os = httpServletResponse.getOutputStream();
byte[] buffer = new byte[1 << 12];
int bytesRead = -1;
try (FileInputStream fis = new FileInputStream(path)) {
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
os.flush();
}
} catch (Exception e) {
httpServletResponse.setContentType("text/html; charset=UTF-8");
os.write(("path " + path + " does not exist").getBytes(StandardCharsets.UTF_8));
os.flush();
}
return;
}
}
Das folgende Listing zeigt die Spring Boot Application:package ch.std.fileservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GenericFileServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GenericFileServiceApplication.class, args);
}
}
http://localhost:8080/rest/file?path=/mypath/myfile.txt
Sofern das File existiert wird es zum Client gestreamt.