Implemented using Spring MVC, rest service.
Display file on screen or download as attachment.
@Controller
public class FileController
{
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "/file/{id}", method = RequestMethod.GET)
public void getFileViaAttachment(@PathVariable String id, HttpServletResponse response)
{
log.info("getFile " + id);
try
{
String content = "testing file download";
String fileName = "mojFileIzStringa.txt";
InputStream in = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
IOUtils.copy(in, response.getOutputStream());
response.setContentType("application/text");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.flushBuffer();
}
catch (IOException e)
{
e.printStackTrace();
}
}
@RequestMapping(value = "/many", method = RequestMethod.GET)
public void getManyLinesViaAttachment(HttpServletResponse response)
{
log.info("getManyLines ");
try
{
String[] linesArrays = { "prva linija", "druga linija", "xxx linija" };
List<String> linesList = Arrays.asList(linesArrays);
String fileName = "mojFileSpunoLinija.csv";
IOUtils.writeLines(linesList, null, response.getOutputStream(), StandardCharsets.UTF_8);
response.setContentType("application/text");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.flushBuffer();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// every line in new row
@RequestMapping(value = "/getFileAsItIs", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public String getFileAsItIs()
{
log.info("getFileAsItIs ");
String[] linesArrays = { "prva linija", "druga linija", "xxx linija" };
List<String> linesList = Arrays.asList(linesArrays);
StringBuilder sb = new StringBuilder();
for (String s : linesList)
{
sb.append(s).append(System.lineSeparator());
}
return sb.toString();
}
}
No comments:
Post a Comment