2016-07-08 39 views
0

我試圖發送一些內容作爲下載的txt文件,但是文件在瀏覽器本身中打開,而不是作爲下載發送。這是我的一段代碼: -文件內容顯示在瀏覽器窗口中,而不是作爲下載文件發送

StreamResource res = new StreamResource(new StreamSource() { 

     @Override 
     public InputStream getStream() { 
      StringBuffer buf = new StringBuffer(); 
      for (String record : records) 
       buf.append(record); 
      ByteArrayInputStream is = new ByteArrayInputStream(new String(buf).getBytes()); 
      return is; 
     } 
    }, filenameReport, app); 
    res.setMIMEType("text/plain"); 
    res.getStream().setParameter("Content-Disposition", "attachment; filename=" + filenameReport); 
    btnGet.getWindow().open(res); 

回答

1

打開窗口不打開一個窗口(這就是爲什麼它的命名方式)

使用文件描述here

FileDownloader類的基本用途是這個:

public class LettingUserDownladFile extends UI { 

    @Override 
    protected void init(VaadinRequest request) { 
     Button downloadButton = new Button("Download image"); 

     StreamResource myResource = createResource(); 
     FileDownloader fileDownloader = new FileDownloader(myResource); 
     fileDownloader.extend(downloadButton); 

     setContent(downloadButton); 
    } 

    private StreamResource createResource() { 
     return new StreamResource(new StreamSource() { 
      @Override 
      public InputStream getStream() { 
       String text = "My image"; 

       BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR); 
       bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20); 

       try { 
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        ImageIO.write(bi, "png", bos); 
        return new ByteArrayInputStream(bos.toByteArray()); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        return null; 
       } 

      } 
     }, "myImage.png"); 
    } 

} 
+0

但我的項目是vaadin 6 ...我無法遷移到vaadin 7爲此 –

+0

來回vaadin 6你可能會與內容類型「APPLICAT的嘗試離子/未知」 –

相關問題