[英]Download file from servlet through browser
我應該通過瀏覽器從服務器下載一個csv文件。 我嘗試使用以下代碼的servlet
private void writeFile(String filename, String content, HttpServletResponse response) throws IOException {
String filename="VR.csv";
try {
File file = new File(filename);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
}
catch(IOException e) {
e.printStackTrace();
}
// This should send the file to browser
ServletOutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(filename);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
System.out.println("done");
}
但是該程序沒有下載Download文件夾中的任何文件,該程序讓我在瀏覽器中看到csv內容。 我需要在瀏覽器的下載文件夾中有VR.csv。
您沒有設定回應! 如果要下載特定文件,則需要在響應中指定要下載的類型和特定文件的路徑。
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment;filename=yourFileName.csv");
除了先前的答案,您的方法還應該具有返回類型,就像您使用Spring Framework一樣,它應該具有ModelAndView,如下所示
公共ModelAndView writeFile(字符串文件名,字符串內容,HttpServletResponse響應)引發IOException {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.