本文实例讲述了jsp实现远程文件下载保存到服务器指定目录中的方法。分享给大家供大家参考,具体如下:
<%@page import="java.net.*,java.io.*"%>
<%!
public boolean saveurlas(string photourl, string filename) {
//此方法只能用户http协议
try {
url url = new url(photourl);
httpurlconnection connection = (httpurlconnection) url.openconnection();
datainputstream in = new datainputstream(connection.getinputstream());
dataoutputstream out = new dataoutputstream(new fileoutputstream(filename));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
return true;
}
catch (exception e) {
return false;
}
}
public string getdocumentat(string urlstring) {
//此方法兼容http和ftp协议
stringbuffer document = new stringbuffer();
try {
url url = new url(urlstring);
urlconnection conn = url.openconnection();
bufferedreader reader = new bufferedreader(new inputstreamreader(conn.
getinputstream()));
string line = null;
while ( (line = reader.readline()) != null) {
document.append(line + "n");
}
reader.close();
}
catch (malformedurlexception e) {
system.out.println("unable to connect to url: " + urlstring);
}
catch (ioexception e) {
system.out.println("ioexception when connecting to url: " + urlstring);
}
return document.tostring();
}
%>
<%
//测试
string photourl = "http://ad4.sina.com.cn/200601/12/43932_750450.jpg";
string filename = photourl.substring(photourl.lastindexof("/"));
string filepath = "c:/test/";
boolean flag = saveurlas(photourl, filepath + filename);
out.println("run ok!n<br>get url file " + flag);
%>
希望本文所述对大家jsp程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!