1、javascript代码如下,filePath为服务器路径:
var stream =newActiveXObject("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();
xmlhttp = newXMLHttpRequest();
if(xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType("text/xml")
}
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.setRequestHeader("Content-Length", stream.Size);
if (xmlhttp.status ==200) {
var responseText = xmlhttp.responseText;
dbfdata =responseText;
} else
{
alert("系统错误");
}
function sendFileToServer(filePath){
}
//辅助JS函数:将服务器端文件下载到客户端本地
var dbfdata;
function sendByteStreamToServer(stream,url){
if (window.XMLHttpRequest) {
} else if (window.ActiveXObject) {
}
xmlhttp.onreadystatechange = callback_upload;
xmlhttp.open("post", url, false);
boundary="abcd"
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data,boundary="+boundary);
xmlhttp.send(stream);
}
//得到数据
function callback_upload() {
if (xmlhttp.readyState == 4) {
}
}
2、JAVA后台代码:把文件读到本地
String cmd = request.getParameter("cmd");
OutputStream ou = (OutputStream)response.getOutputStream();
if ("upload".equalsIgnoreCase(cmd)) {
String filePath = newString(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);
StringtempPath=(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(newFileOutputStream(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();