简体   繁体   English

在Java Servlet中下载CSV文件

[英]Download CSV file in Java Servlet

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();

I need to download a csv file but it seems to return "java.lang.IllegalStateException: WRITER" 我需要下载一个csv文件,但它似乎返回“ java.lang.IllegalStateException:WRITER”

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

UPDATE 更新

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

I still get the same error. 我仍然遇到相同的错误。 java.lang.IllegalStateException: WRITER java.lang.IllegalStateException:WRITER

(drunk) Why am I getting this error >_< (醉酒)我为什么收到此错误> _ <

Try this: 尝试这个:

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

java/servlet code you supplied works perfectly fine. 您提供的java / servlet代码可以很好地工作。 i call the servlet CSVD as below: 我将servlet称为CSVD,如下所示:

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

or through anchor this way < a href="/CSVDownloadApp/CSVD">click here to download csv< /a> 或通过锚定方式<a href =“ / CSVDownloadApp / CSVD”>单击此处下载csv </ a>

possibly your error is coming for a different reason. 可能是由于其他原因导致您的错误。

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

And the stream method should be like this. 流方法应该是这样的。

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

} }

Try this: 尝试这个:

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

For writing the file in OutputStream, try following 要在OutputStream中写入文件,请尝试以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM