Java enables uploading files across servers
- 2020-12-21 18:03:17
- OfStack
A few days ago, I was working on a project. The client side and the administrator side were written on the same server. All the files uploaded by the client were stored on the hard disk of the server. Lao Long proposed to separate the client side and the administrator side, at this time the user uploaded attachments storage problems. Obviously, it is not practical to save apk files up to several hundred M files to the database. After a long search, it is the fastest way to set up ftp servers on both ends to transfer files.
The specific process is that the user logs in to the external client and uploads the file to the external server's hard disk. At the same time, the file accesses the ftp server of the internal network administrator server through the external server and transfers it to the internal server's hard disk. In this way, the internal server can encrypt and sign the uploaded files, and then send the files back to the external server's hard disk through ftp for other operations by users.
Specific implementation of the tool: ES10en-ES11en. Serv-U is a tool for setting up ftp servers on windows. After downloading and cracking, follow the steps to set up Ip, port, account password, disk path that allows ftp access, operation permission, etc., and you are ready to use. IP selected 127.0.0.1 for local test and 192.168.0.0.x for Intranet test.
In the implementation of java project, I wrote my own tool class, which uses commons-ES25en package, with upload, download and delete functions. Attached code:
package app.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* FTP Server tools class
*
*/
public class FTPUtils {
/**
* Upload file to FTP The server
*
* @param url
* The server IP address
* @param port
* Server port
* @param userName
* User login name
* @param password
* User login password
* @param storePath
* Server file storage path
* @param fileName
* Server file storage name
* @param is
* File input stream
* @return
* <b>true</b> : Upload successful
* <br/>
* <b>false</b> : Upload failed
*/
public static boolean storeFile (String url, int port, String userName, String password, String storePath, String fileName, InputStream is) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
// Connect to the server, the port is default 21 Can be directly through URL The connection
ftp.connect(url ,port);
// Login server
ftp.login(userName, password);
// Determine if the return code is valid
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
// Disconnect when illegal
ftp.disconnect();
// End of the program
return result;
}
// judge ftp Whether a directory exists, or if not, create a directory, including creating multiple levels of directories
String s = "/"+storePath;
String[] dirs = s.split("/");
ftp.changeWorkingDirectory("/");
// Check that the directory exists in order, or create it if it doesn't
for(int i=1; dirs!=null&&i<dirs.length; i++) {
if(!ftp.changeWorkingDirectory(dirs[i])) {
if(ftp.makeDirectory(dirs[i])) {
if(!ftp.changeWorkingDirectory(dirs[i])) {
return false;
}
}else {
return false;
}
}
}
// Set the file action directory
ftp.changeWorkingDirectory(storePath);
// Set the file type, 2 Into the system
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// Set buffer size
ftp.setBufferSize(3072);
// Upload a file
result = ftp.storeFile(fileName, is);
// Close the input stream
is.close();
// Log out of server
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Determine if the input stream exists
if (null != is) {
// Close the input stream
is.close();
}
// Determine if the connection exists
if (ftp.isConnected()) {
// disconnect
ftp.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* from FTP The server downloads the file locally
*
* @param url
* The server IP address
* @param port
* Server port
* @param userName
* User login name
* @param password
* User login password
* @param remotePath
* Server file storage path
* @param fileName
* Server file storage name
* @param localPath
* Local file storage path
* @return
* <b>true</b> : Download successful
* <br/>
* <b>false</b> : Download failed
*/
public static boolean retrieveFile (String url, int port, String userName, String password, String remotePath, String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
OutputStream os = null;
try {
// Connect to the server, the port is default 21 Can be directly through URL The connection
ftp.connect(url ,port);
// Login server
ftp.login(userName, password);
// Determine if the return code is valid
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
// Disconnect when illegal
ftp.disconnect();
// End of the program
return result;
}
// Set the file action directory
ftp.changeWorkingDirectory(remotePath);
// Set the file type, 2 Into the system
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// Set buffer size
ftp.setBufferSize(3072);
// Set character encoding
ftp.setControlEncoding("UTF-8");
// Construct the local file object
File localFile = new File(localPath + "/" + fileName);
// Gets all file names in the file action directory
String[] remoteNames = ftp.listNames();
// Loop through the file name to see if it contains the file name you are currently downloading
for (String remoteName: remoteNames) {
if (fileName.equals(remoteName)) {
result = true;
}
}
// When file name matching is successful, enter the download process
if (result) {
// Construct the file output stream
os = new FileOutputStream(localFile);
// The download file
result = ftp.retrieveFile(fileName, os);
// Close the output stream
os.close();
}
// Log out of server
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Determine if an output stream exists
if (null != os) {
// Close the output stream
os.close();
}
// Determine if the connection exists
if (ftp.isConnected()) {
// disconnect
ftp.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* from FTP Server delete file
*
* @param url
* The server IP address
* @param port
* Server port
* @param userName
* User login name
* @param password
* User login password
* @param remotePath
* Server file storage path
* @param fileName
* Server file storage name
* @return
* <b>true</b> : Deleted successfully
* <br/>
* <b>false</b> : Delete failed
*/
public static boolean deleteFile (String url, int port, String userName, String password, String remotePath, String fileName) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
// Connect to the server, the port is default 21 Can be directly through URL The connection
ftp.connect(url ,port);
// Login server
ftp.login(userName, password);
// Determine if the return code is valid
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
// Disconnect when illegal
ftp.disconnect();
// End of the program
return result;
}
// Set the file action directory
ftp.changeWorkingDirectory(remotePath);
// Set the file type, 2 Into the system
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// Set buffer size
ftp.setBufferSize(3072);
// Set character encoding
ftp.setControlEncoding("UTF-8");
// Gets all file names in the file action directory
String[] remoteNames = ftp.listNames();
// Loop through the file name to see if it contains the file name you are currently downloading
for (String remoteName: remoteNames) {
if (fileName.equals(remoteName)) {
result = true;
}
}
// When file name matching is successful, enter the delete process
if (result) {
// Delete the file
result = ftp.deleteFile(fileName);
}
// Log out of server
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Determine if the connection exists
if (ftp.isConnected()) {
// disconnect
ftp.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
// try {
// FileInputStream fis = new FileInputStream(new File("D:/Soft Storage/ Software toolbox /HTML_Help_WorkShop_1.3_XiaZaiBa.zip"));
// System.out.println(storeFile("192.168.1.2", 21, "admin", "1", "C:/Documents and Settings/Administrator/ desktop ", RandomUUID.random() + ".zip", fis));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
//
//File file = new File("C:/Users/freed/Desktop/1.txt");
//InputStream is = new FileInputStream(file);
//System.out.println(storeFile("127.0.0.1", 21, "feili", "feili", "examples", "2.txt", is));
//System.out.println(retrieveFile("127.0.0.1", 21, "feili", "feili", "examples/jsp", "index.html", "C:/Users/freed/Desktop"));
//System.out.println(deleteFile("127.0.0.1", 21, "feili", "feili", "testpath", "1.txt"));
}
}
It should be noted that the File file should be placed in fileinputstream before uploading the file.