java Servlet Download File example

想在 client side 取得 server side 的檔案. 我找到個的範例.

Example 1:

PrintWriter out=response.getWriter();
String fileName="home.txt";
String filePath="d:\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment;fileName=\""+fileName+"\"");
int in;
FileInputStream file=new FileInputStream(filePath +fileName);
while((in=file.read()) !=-1){
	out.write(in);
}
file.close();
out.close();

Example 2:

File downloadFile = new File(filePath);
FileInputStream inStream = null;
try {
	inStream = new FileInputStream(downloadFile);
} catch (FileNotFoundException e) {
	e.printStackTrace();
}

if(inStream!=null) {
	String mimeType = "application/octet-stream";
	response.setContentType(mimeType);
	response.setContentLength((int) downloadFile.length());

	String headerKey = "Content-Disposition";
	String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
	response.setHeader(headerKey, headerValue);
	 
	ServletOutputStream outStream;
	try {
		outStream = response.getOutputStream();
		
    	byte[] buffer = new byte[4096];
    	int bytesRead = -1;
    	 
    	while ((bytesRead = inStream.read(buffer)) != -1) {
    	    outStream.write(buffer, 0, bytesRead);
    	}
    	outStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	 
	try {
		inStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *