2013-12-17 46 views
1

現在可以從Spring控制器下載文件,但沒有對話框,並且該文件直接保存到瀏覽器的下載文件夾中。我想要一個文件對話框,詢問用戶要保存哪個文件夾。怎麼做?代碼是如何從Spring控制器創建文件保存對話框?

@RequestMapping(value = "/export", method = RequestMethod.GET) 
@ResponseBody 
public ModelAndView export(HttpServletResponse response) { 
    try { 
     String str = "sep=\t\n"; // tells excel what the delimiter character should be 
     Iterator<Individual> iterator = customerAccountService.getAllIndividuals().iterator(); 
     while(iterator.hasNext()){ 
      Individual individual = iterator.next(); 
      str = str + individual.getId() + "\t" +individual.getIndividualName().getName() + "\t" + individual.getAddress().getStreetName() + "\n"; 
     } 
     InputStream is = new ByteArrayInputStream(str.getBytes()); 
     IOUtils.copy(is, response.getOutputStream()); 
     response.setContentType("application/xls"); 
     response.setHeader("Content-Disposition","attachment; filename=Users-export.csv"); 
     response.flushBuffer(); 
    } catch (IOException ex) { 
     //logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); 
     throw new RuntimeException("IOError writing file to output stream"); 
    } 
    ModelAndView modelAndView = new ModelAndView(ViewName.MENU); 
    modelAndView.addObject(ObjectName.ADD_FORM, new LoginForm()); 
    return modelAndView; 
} 

回答

1

你必須記住,你的Spring Web應用程序是一個HTTP兼容的應用程序。 HTTP是一個請求 - 響應協議。客戶端發送請求,服務器發送響應。

在你的情況下,響應看起來像這樣

HTTP/1.1 200 OK 
Content-Disposition: attachment; filename=Users-export.csv 
Content-Type: application/xls 
Content-Length: XYZ 

<bytes goes here> 

您的客戶端,瀏覽器,將收到這一點,並盡一切可能與它選擇。您應該檢查您的瀏覽器設置並啓用Save As...提示。


無法從Web應用程序強制執行瀏覽器提示。