我已经解析了一个使用POST发送到我的TOMCAT服务器的JSON对象,并将其转换为CSV文件。我想将CSV文件发回给用户。我对如何发送文件感到困惑,因为我看到的所有示例都引用了存储在服务器上的实际文件 - 我的文件内置在内存中并且实际上并没有引用文件/文件描述符我可以告诉你。
//The doPost method has already generated the String[] - I then call generateCSV
protected void generateCSV(ArrayList<String[]> data, ServletOutputStream out,
HttpServletResponse response)
{
try{
BufferedWriter buff = new BufferedWriter(new OutputStreamWriter(out));
CSVWriter writer = new CSVWriter(buff);
writer.writeAll(data);
writer.close();
sendFile(response, out);
}catch(IOException | ServletException e){
e.printStackTrace();
}
}
protected void sendFile(HttpServletResponse response, ServletOutputStream outstream)throws ServletException, IOException
{
response.setContentType("application/octet-stream");
outstream.flush();
outstream.close();
}
答案 0 :(得分:1)
从servlet向用户发送文件需要做什么?
对我来说,你这样做,但顺序错误。此外,您可能希望实际告诉浏览器这是CSV,而不是使用application / octet-stream。您可能还想给它一个文件名。
response.setContentType("text/csv");
response.setHeader("Content-Disposition","filename=whatever.csv");
BufferedWriter buff = new BufferedWriter(new OutputStreamWriter(out));
CSVWriter writer = new CSVWriter(buff);
writer.writeAll(data);
writer.close();