Method of Downloading and Saving Remote Files to Designated Directory of Server by JSP
- 2021-09-12 01:48:20
- OfStack
This article example describes the JSP implementation of the remote file download saved to the server specified directory method. Share it for your reference, as follows:
<%@page import="java.net.*,java.io.*"%>
<%!
public boolean saveUrlAs(String photoUrl, String fileName) {
// This method can only be used by users HTTP Agreement
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) {
// This method is compatible with HTTP And FTP Agreement
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();
}
%>
<%
// Test
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);
%>
I hope this article is helpful to everyone's JSP programming.