applet文件上传下载
查看文章js调用applet实现上传下载(1)2009-09-24 10:09用js调用applet实现文件的上传,下载。
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[i].getBytes("ISO-8859-1"),"utf-8");
String fn=new String(fName[i].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="上传" onclick="tsb('<%=i %>')">
</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来发送流和读取流。以及把文件转换成流或把流转换成文件的操作。
--------------------编程问答-------------------- 怎么没有看到下载的呢?
补充:Java , Java相关