quick-cocos2d-x下載檔案

iteye_21202發表於2013-05-28

伺服器端仍然是一個servlet,程式碼如下:

public class DownServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String path = "D:/Downloads/LuaXML_101012.zip";
		File file = new File(path);
		InputStream is = new BufferedInputStream(new FileInputStream(file));
		byte[] buffer = new byte[is.available()];
		is.read(buffer);
		is.close();
		response.reset();
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(file.getName().getBytes("utf-8"), "ISO-8859-1"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
	}

}

下面是客戶端lua指令碼:

local function callback1(event)
	local ok = (event.name == "completed")
	local request = event.request
	request:saveResponseData("a.zip")
	
end

local request1 = network.createHTTPRequest(callback1, "http://localhost:8080/download", "POST")
request1:start()

說明:http://....../download是上面servlet的響應url,當Lua訪問此url時,伺服器將檔案資料傳送到客戶端。