在Java Servlet中下载CSV文件

时间:2015-03-16 05:44:08

标签: java csv servlets

String fileName = "/CSVLogs/test";
         String fileType = "csv";
         resp.setContentType(fileType);

         resp.setHeader("Content-disposition","attachment; filename=test.csv");

         File my_file = new File(fileName);

         OutputStream out = resp.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();

我需要下载一个csv文件,但它似乎返回" java.lang.IllegalStateException:WRITER"

<form enctype="multipart/form-data" action="/TestServlet/ConfigServlet?do=downloadLogs" method="post" style="height:68px;">
  

更新

resp.setContentType("application/octet-stream");
            try
            {
                OutputStream outputStream = resp.getOutputStream();
                InputStream in = StorageUtil.getInstance().getFile("/CSVLogs/test.csv").getInputStream();
            /*    InputStream in = StorageUtil.getInstance().getCSVLogsZip().getInputStream();*/
                byte[] buffer = new byte[4096];
                 int length;
                 while ((length = in.read(buffer)) > 0){
                    outputStream.write(buffer, 0, length);
                    in.close();
                    outputStream.flush();
                 }
            }
            catch(Exception e) {
                System.out.println(e.toString());
            }

我仍然得到同样的错误。 java.lang.IllegalStateException:WRITER

(醉)为什么我收到此错误&gt; _&lt;

4 个答案:

答案 0 :(得分:1)

试试这个:

public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
try
{
    OutputStream outputStream = response.getOutputStream();
    FileInputStream in = new FileInputStream(my_file);
    byte[] buffer = new byte[4096];
     int length;
     while ((length = in.read(buffer)) > 0){
        outputStream.write(buffer, 0, length);
 in.close();
     outputStream.flush();
     }
}
catch(Exception e)
{
    model.closeConnection();
    System.out.println(e.toString());
    }
}

答案 1 :(得分:1)

你提供的java / servlet代码完全正常。 我将servlet称为CSVD,如下所示:

< form enctype="multipart/form-data" action="CSVD" method="post" style="height:68px;">
<input type="submit" value="submit" />
< /form>

或以这种方式锚定&lt; a href =“/ CSVDownloadApp / CSVD”&gt;点击此处下载csv&lt; / A&GT;

可能你的错误也是出于其他原因。

答案 2 :(得分:1)

public void downloadFile(HttpServletResponse response){ 
    String sourceFile = "c:\\source.csv";
    try {
        FileInputStream inputStream = new FileInputStream(sourceFile);
        String disposition = "attachment; fileName=outputfile.csv";
        response.setContentType("text/csv");
        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);
    }
}

并且stream方法应该是这样的。

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;
}

}

答案 3 :(得分:0)

试试这个:

response.setContentType("application/x-rar-compressed");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");

要在OutputStream中写入文件,请尝试按照

FileInputStream fis = new FileInputStream("your_csv_file.csv");
byte[] b = new byte[fis.available()];
outputStream.write(b);
outputStream.flush();
outputStream.close();