ActiveXObject可实现客户端从服务器端下载文件到本地的功能



ActiveXObject可实现客户端从服务器端下载文件到本地的功能

1、javascript代码如下,filePath为服务器路径:

function sendFileToServer(filePath){
var stream =new ActiveXObject(“ADODB.Stream”);
stream.Type=1;
stream.Open();
stream.Position = 0;
stream.LoadFromFile(filePath) //可以读取服务器端文件,并下载到本地指定路径
stream.Position = 0;
sendByteStreamToServer(stream,appRoot+”/uploadServlet?cmd=upload&filePath=”+filePath);
stream.Close();
}
//辅助JS函数:将服务器端文件下载到客户端本地
var dbfdata;
function sendByteStreamToServer(stream,url){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(“text/xml”)
}
} else if (window.ActiveXObject) {
var activexName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
for (var i = 0; i < activexName.length; i++) {
try {
xmlhttp = new ActiveXObject(activexName[i]);
break;
} catch(e) {
e.print();
}
}
}
xmlhttp.onreadystatechange = callback_upload;
xmlhttp.open(“post”, url, false);
boundary=”abcd”
xmlhttp.setRequestHeader(“Content-Type”, “multipart/form-data, boundary=”+boundary);
xmlhttp.setRequestHeader(“Content-Length”, stream.Size);
xmlhttp.send(stream);
}

//得到数据
function callback_upload() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var responseText = xmlhttp.responseText;
dbfdata =responseText;
} else
{
alert(“系统错误”);
}
}
}

2、JAVA后台代码:把文件读到本地

String cmd = request.getParameter(“cmd”);
OutputStream ou = (OutputStream) response.getOutputStream();
if (“upload”.equalsIgnoreCase(cmd)) {
String filePath = new String(request.getParameter(“filePath”).getBytes(“iso8859-1″), “GBK”);
String fileName = filePath.substring(filePath.lastIndexOf(“\\”) + 1);
String loadPath =Constant.ROOTPATH + “upload_files” + System.getProperties().getProperty(“file.separator”); // 上传文件存放目录
InputStream in = request.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
String tempPath=(String)request.getSession().getAttribute(“tempPath”);
if(tempPath==null||tempPath.equalsIgnoreCase(“”)){
tempPath=UUID.randomUUID().toString();
request.getSession().setAttribute(“tempPath”, tempPath);
}
loadPath=loadPath+tempPath+System.getProperties().getProperty(“file.separator”);
File newFile = new File(loadPath);
if (!newFile.exists())
newFile.mkdirs();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(loadPath + fileName.toLowerCase())));// 获得文件输出流
int b = 0;
while ((b = bis.read()) != -1) {
bos.write(b);
}
in.close();
bis.close();
bos.close();
ou.write(tempPath.getBytes());
ou.close();