JApplet端示例
URLConnection con;try {//url是被调用的SERVLET的网址 如 *.docon = url.openConnection();con.setUseCaches(false);con.setDoInput(true);con.setDoOutput(true);con.setRequestProperty("Content-Type","application/octet-stream");InputStream in = con.getInputStream();ProgressMonitorInputStream pmInputStream = new ProgressMonitorInputStream(pane, "正在从服务器下载文件内容", in);ProgressMonitor pMonitor = pmInputStream.getProgressMonitor();pMonitor.setMillisToDecideToPopup(3);pMonitor.setMillisToPopup(3);//localfilepath本地路径,localstr文件文件夹,filename本地文件名String localfilepath = localstr + filename ;//方法saveFilsaveFilee是把输入流pmInputStream写到文件localfilepath中if(saveFilsaveFilee(localfilepath,pmInputStream)){openLocalFile(localfilepath);}
4.顺便把JApplet上传文件的代码也贴上来.
JApplet端示例
URLConnection con;try {con = url.openConnection();//url是被调用的SERVLET的网址 如 *.docon.setUseCaches(false);con.setDoInput(true);con.setDoOutput(true);con.setRequestProperty("Content-Type","application/octet-stream"); OutputStream out = con.getOutputStream();//localfilepath本地路径,localstr文件文件夹,filename本地文件名String localfilepath = localstr + filename;//文件getOutputStream是把文件localfilepath写到输出流out中getOutputStream(localfilepath,out);InputStream in = con.getInputStream();return true;}catch (IOException e) { System.out.println("文件上传出错!");e.printStackTrace();}
servlet端代码示例
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {res.setContentType(" text/plain ");InputStream inputStream = null;try {inputStream = res.getInputStream();//把输入流inputStream保存到文件路径为srcFile的文件中writefile(srcFile, inputStream);} catch (IOException e) {e.printStackTrace();}} // end service
总结:在文件的传输中是流的形式存在的,在硬盘上是文件的形式存在的。我们要做的只是通过HttpServletRequest和HttpServletResponse,或者是response和request来发送流和读取流。以及把文件转换成流或把流转换成文件的操作。