js调用applet实现和Servlet的数据和文件上传下载


http://www.g4studio.org/thread-766-1-1.html

1.上传的代码:

applet代码


package applet;
import java.applet.Applet;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
//本地文件上传(与Servlet交互)
public class AppInt extends Applet {

private String filePath;
private String fileName;
private String url;

private boolean bl=false;
public String getFilePath() {
    return filePath;
}
public void setFilePath(String filePath) {
    this.filePath = filePath;
    System.out.println(this.filePath);
}
public String getFileName() {
    return fileName;
}
public void setFileName(String fileName) {
    this.fileName = fileName;
    System.out.println(this.fileName);
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
    System.out.println(this.url);
}
public void setBl(){
    this.bl=true;
    System.out.println(this.bl);
    send();
}

public void init() {   
    if(this.bl){
     send();
    }
}

public void send() {
    {
     try {
      String filePath=getFilePath();
      String fileName =getFileName();   
      String urlstring=getUrl();
      System.out.println(filePath+"*****");
    //网络路径很重要
    URL url1 = new URL(urlstring+"?fileName="+URLEncoder.encode(fileName,"utf-8"));
    //打开打开SOCKET链接
   
      HttpURLConnection conn = (HttpURLConnection) url1
      .openConnection();
    conn.setRequestMethod("POST");
    conn.setAllowUserInteraction(true);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(true);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
  
    File jpgFile = new File(filePath);
    if (jpgFile.isFile()) {
    // 建立文件的输入流
     FileInputStream fileInputStream = null;
     fileInputStream = new FileInputStream(jpgFile);
     BufferedInputStream bis = new BufferedInputStream(
       fileInputStream);
     OutputStream os = conn.getOutputStream();
     BufferedOutputStream bos = new BufferedOutputStream(os);
     int len = 0;
     byte[] bty = new byte[4096];
     while ((len = bis.read(bty, 0, 4096)) != -1) {
      bos.write(bty, 0, len);
      bos.flush();
     }
     bos.close();
     bis.close();
     System.out.println(conn.getContentType() + ": "+ conn.getResponseCode());
    }
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
}
}


对应的Servlet代码:

package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.DB.DBconnect;
public class Receive extends HttpServlet {

public Receive() {
    super();
}

public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    // PrintWriter out=response.getWriter();
    InputStream in = request.getInputStream();         
          //System.out.print("qqqq");
  
      
    String name=new String(request.getParameter("fileName").getBytes(),"utf-8");
   
    String nn=new String(name.getBytes("ISO8859-1"),"utf-8");
    System.out.println("文件名:"+name+"******"+nn);
   
    String tr=name.substring(name.lastIndexOf("."),name.length());
  
   // 根据时间得文件名
      Calendar calendar = Calendar.getInstance();
      String filename = String.valueOf(calendar.getTimeInMillis())
        +tr;
      
    System.out.println("服务器,文件名:"+name);
   
          File f = new File("C:\\imgrec\\"+filename);
          String path="c:/imgrec/"+filename;
          FileOutputStream fos = new FileOutputStream(f);
           byte[] b = new byte[1024 * 1024];
           int bytes, sumBytes = 0;
           while (true) {
               bytes = in.read(b);
               if (bytes <= 0)
                   break;
               sumBytes += bytes;
               fos.write(b, 0, bytes);
           }
           fos.close();
           in.close();
           
           
           /*
            * 保存上传记录
            */
           DBconnect dao=new DBconnect();
           String sql="insert into fileList(fileName,filePath,name) values('"+filename+"','"+path+"','"+name+"')";
           dao.save(sql);
           dao.close();
         
          }

public void init() throws ServletException {
}
}

JSP页面:

<%@ page language="java" import="java.util.*,applet.GLAppInt" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
     
     
     <title>test.jsp</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">     
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body >
<APPLET    CODE = "applet.GLAppInt.class" archive="applet.jar" height="90%" MAYSCRIPT>
<param name="path" value="E:\test\upload">
</APPLET>
<script type="text/javascript">
function saveHtml(){
var filePath=document.applets[0].getAn();
var fileName=document.applets[0].getName();
//alert(fileName);
document.location="show.jsp?filePath="+filePath+"&fileName="+fileName;
}

</script>


</body>

</html>
//*************************
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
     <base href="<%=basePath%>">
     
     <title>My JSP 'show.jsp' starting page</title>
     
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">     
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
   
   
     <%
    String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/appUpFile/servlet/Receive" ;
    String filePath=request.getParameter("filePath");
   
    if(filePath.length()>0){
    String fileName=request.getParameter("fileName");
    String[] fPath=filePath.split(",");
    String[] fName=fileName.split(",");
   
   
    %>
    <div>
     <APPLET    CODE = "applet.AppInt.class" archive="ctr.jar" mayscript height="1" width="1">   
         </APPLET>
     <script type="text/javascript">
     function tsb(n){
       var fn=document.getElementById('fn'+n).value;
       var fp=document.getElementById('fp'+n).value;
       var ul='<%=url%>';
      document.applets[0].setFileName(fn);
      document.applets[0].setFilePath(fp);
      document.applets[0].setUrl(ul);
      document.applets[0].setBl();
     }
    </script>
    </div>
   
    <div align='center'>本地文件上传</div>
     <form action="">
     <table>
     <tr>
     <td>文件名</td>
     <td>路径</td>
     <td>上传</td>
     </tr>
     <%
     for(int i=0;i<fName.length;i++){
    String fp=new String(fPath.getBytes("ISO-8859-1"),"utf-8");
     String fn=new String(fName.getBytes("ISO-8859-1"),"utf-8");
   
     %>
     <tr>
     <td><input type="hidden" name="fn<%=i %>" id="fn<%=i %>" value="<%=fn %>"><%=fn %></td>
     <td><input type="hidden" name="fp<%=i %>" id="fp<%=i %>" value="<%=fp %>"><%=fp %></td>     
     <td><input type="button" name="sb" value="上传">
     </td>
     </tr>
     <%
     }
     %>
     </table>
     </form>
<%
}
%>

</body>
</html>






数据库设计:

fileList表:有4个字段 id,fileName,filePath ,name

package com.DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBconnect {
public static Connection conn = null;
public DBconnect() {
    this.conn = getMySqlConnection();
}
public static Connection getMySqlConnection() {
    String url = null;
    try {
     Class.forName("com.mysql.jdbc.Driver");
     url = "jdbc:mysql://localhost:3306/listenle?useUnicode=true&characterEncoding=UTF-8";
     conn = DriverManager.getConnection(url, "root", "rufeng8848");
    } catch (Exception e) {
     e.printStackTrace();
    }
    return conn;
}
/*
* 插入表fileList 给每一次上传的文件做好记录
* 记录上传
*/
public void save(String sql){
    Statement st=null;
  
    try {
     st=conn.createStatement();
     st.execute(sql);
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
}
/*
* 取出fileList表中 文件名,路径
* 便于下载
* 返回类型为
*/
public ResultSet findAll(){
    ResultSet rs=null;
    Statement st=null;
    String sql="select * from fileList";
    try {
     st=conn.createStatement();
     rs=st.executeQuery(sql);
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    return rs;
}
/*
* 关闭链接
*/
public void close() {
    try {
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
     System.out.println("关闭异常");
    }
}
}

这样就可以上传了。
经过测试发现,JS调用applet报java.security.accesscontrolexception异常。
原来是安全机制的问题。在客户端修改一下java的安全机制就可以了。
总结:在文件的传输中是流的形式存在的,在硬盘上是文件的形式存在的。我们要做的只是通过HttpServletRequest和HttpServletResponse,或者是response和request来发送流和读取流。以及把文件转换成流或把流转换成文件的操作
现在该下载了:
下载的代码如下:
applet代码

package applet;
import java.applet.Applet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.swing.ProgressMonitor;
import javax.swing.ProgressMonitorInputStream;
public class Down extends Applet {
private String filePath;
private String fileName;
private String url;
private boolean bl=false;

public String getFilePath() {
    return filePath;
}
public void setFilePath(String filePath) {
    this.filePath = filePath;
    System.out.println(this.filePath);
}
public String getFileName() {
    return fileName;
}
public void setFileName(String fileName) {
    this.fileName = fileName;
    System.out.println(this.fileName);
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
    System.out.println(this.url);
}
public void setBl(){
    this.bl=true;
    System.out.println(this.bl);
    download();
}

public void init() {
}
public void download() {
    try {
     String filePath=getFilePath();
     String fileName =getFileName();   
     String urlstring=getUrl();
     System.out.println(filePath+"*****");
     //网络路径很重要
     URL url1 = new URL(urlstring+"?filePath="+filePath);
     //打开打开SOCKET链接
   
     HttpURLConnection conn = (HttpURLConnection) url1
     .openConnection();
conn.setRequestMethod("POST");
conn.setAllowUserInteraction(true);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
conn.setRequestProperty("Content-Type", "application/octet-stream");
     conn.connect();
     //获取流
       InputStream    is=conn.getInputStream();   
      
       System.out.println("获取流成功*****:"+is.read());
       //取文件类型
       //fileName 完整的文件名
      // String tr=fileName.substring(fileName.lastIndexOf("."),fileName.length());
     File file = new File("E:/test/upload/"+fileName);
     byte line[] = new byte[1024];
     int a;
     String temp = "";
     a = is.read(line);
     FileOutputStream outstream = new FileOutputStream(file);
     while (a != -1) {
      outstream.write(line);
      temp = temp + (new String(line));
      a = is.read(line);
     }
     is.close();
     outstream.close();
    } catch (IOException e) {
    }
}
}




对应的Servlet代码:

package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.DB.DBconnect;
public class DownFile extends HttpServlet {
/**
* Constructor of the object.
*/
public DownFile() {
    super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out
      .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println(" <BODY>");
    out.print("     This is ");
    out.print(this.getClass());
    out.println(", using the GET method");
    out.println(" </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    // PrintWriter out=response.getWriter();
      byte[] buff = new byte[1024];
      boolean cont = true;
      FileInputStream infile = null;
      ServletOutputStream fos=null;
    String filePath=(String)request.getParameter("filePath");
    File fe=new File(filePath);
    try {
       infile = new FileInputStream(fe);
      // fos = new FileOutputStream(fe);
       fos=response.getOutputStream();
      } catch (FileNotFoundException e) {
       System.err.println("没有找到文件");
       System.exit(1);
      }
      int n = infile.read(buff);
      while (n!=-1) {
       try {
         // 从文件读取数据
        fos.write(buff, 0, n); // 写入System.out中
        n=infile.read(buff);
        
       } catch (Exception e) {
        cont = false;
       }
      }
      System.out.println("写入流成功!");
      try {
       infile.close();
       fos.close();
      } catch (IOException e) {
       System.err.println("文件错误");
       System.exit(1);
      }

    //InputStream in = request.getInputStream();         
         //System.out.print("qqqq");
  
      
  
   
      
         
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
    // Put your code here
}
}

JSP代码:

<%@ page language="java" import="java.util.*,com.DB.DBconnect,java.sql.ResultSet" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
     <base href="<%=basePath%>">
     
     <title>下载</title>
     
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">     
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<%
String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/appUpFile/servlet/DownFile";
    DBconnect dao=new DBconnect();
   
    %>
</head>

<body>
     服务器文件下载 <br>
     <div>
     <APPLET    CODE = "applet.Down.class" archive="down.jar" mayscript height="1" width="1">   
         </APPLET>
     <script type="text/javascript">
     function tsb(n){
       var fn=document.getElementById('fn'+n).value;
       var fp=document.getElementById('fp'+n).value;
       var ul='<%=url%>';
      document.applets[0].setFileName(fn);
      document.applets[0].setFilePath(fp);
      document.applets[0].setUrl(ul);
      document.applets[0].setBl();
     }
    </script>
    </div>
   
     <table>
     <tr>
     <td>文件名</td>
     <td>路径</td>
     <td>下载</td>
     </tr>
     <%
     try{
     int i=0;
      ResultSet rs=dao.findAll();
      while(rs.next()){
      %>
      
      
      <tr>
     <td><input type="hidden" name="fn<%=i %>" id="fn<%=i %>" value="<%=rs.getString("name") %>"><%=rs.getString("name") %></td>
     <td><input type="hidden" name="fp<%=i %>" id="fp<%=i %>" value="<%=rs.getString("filePath") %>"><%=rs.getString("filePath") %></td>     
     <td><input type="button" name="sb" value="下载">
     </td>
     </tr>
     
      <%
       //rs.getString("fileName");
      i++;
      }
      }catch(Exception e){
      e.printStackTrace();
      }      
     %>
</table>
<%
    dao.close();
    %>
     
</body>
</html>

OK下载搞定了


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值