本例子以servlet为主。
下面是大概思路
public
class
FtpServlet
extends
HttpServlet{
@Override
protected
void
doGet(HttpServletRequest
request
, HttpServletResponse
response
)
throws
IOException, ServletException {
response
.setContentType(
"text/html"
);
String
remotePath
=
request
.getParameter(
"remotePath"
);//ftp路径
String
fileName
=
request
.getParameter(
"fileName"
);//ftp上的文件名称
String
ios
=System.getProperty(
"os.name"
).toLowerCase();//获取系统名称,根据不同系统创建不同的存储路径
String
path
=
""
;
if
(
ios
.indexOf(
"windows"
)>=0){
path
=Configs.get(
"CommonFile.upfile_windows"
);
}
else
{
path
=Configs.get(
"CommonFile.upfile_linux"
);
}
File
mk
=
new
File(
path
);
//如果文件夹不存在则创建
if
(!
mk
.exists() && !
mk
.isDirectory())
{
mk
.mkdir();
}
//远程连接ftp并下载图片到服务器
FtpUtil.downFile(
"10.24.10.36"
, 21,
"fy4"
,
"fy4"
,
remotePath
,
fileName
,
path
);
//读取文件
File
file
=
new
File(
path
+
fileName
);
try
{
FileInputStream
is
;
is
=
new
FileInputStream(
file
);
ServletOutputStream
os
=
response
.getOutputStream();
BufferedOutputStream
bos
=
new
BufferedOutputStream(
os
);
response
.setHeader(
"Content-Disposition"
,
"attachment; filename=\""
+
fileName
+
"\""
);
byte
[]
len
=
new
byte
[1024*2];
int
read
= 0;
while
((
read
=
is
.read(
len
)) != -1){
bos
.write(
len
, 0,
read
);
System.
out
.println(
"read---"
+
read
);
}
bos
.flush();
bos
.close();
is
.close();
}
catch
(Exception
e
) {
e
.printStackTrace();
}
}
}
public
class
FtpUtil {
/**
* Description: 从FTP服务器下载文件
*
*
@param
url
* FTP服务器hostname
*
@param
port
* FTP服务器端口
*
@param
username
* FTP登录账号
*
@param
password
* FTP登录密码
*
@param
remotePath
* FTP服务器上的相对路径
*
@param
fileName
* 要下载的文件名
*
@param
localPath
* 下载后保存到服务器的路径
*
@return
*/
public
static
boolean
downFile(String
url
,
int
port
, String
username
,
String
password
, String
remotePath
, String
fileName
,String
path
) {
boolean
success
=
false
;
FTPClient
ftp
=
new
FTPClient();
int
reply
;
try
{
ftp
.connect(
url
,
port
);
ftp
.login(
username
,
password
);
ftp
.setFileType(FTPClient.
BINARY_FILE_TYPE
);
//文件类型为二进制文件
reply
=
ftp
.getReplyCode();
if
(!FTPReply.isPositiveCompletion(
reply
)) {
ftp
.disconnect();
return
success
;
}
ftp
.enterLocalPassiveMode();
//本地模式
ftp
.changeWorkingDirectory(
remotePath
);
FTPFile[]
fs
=
ftp
.listFiles();
for
(FTPFile
ff
:
fs
) {
if
(
ff
.getName().equals(
fileName
)) {
File
localFile
=
new
File(
path
+
ff
.getName());
OutputStream
is
=
new
FileOutputStream(
localFile
);
ftp
.retrieveFile(
ff
.getName(),
is
);
is
.close();
}
}
ftp
.logout();
success
=
true
;
}
catch
(SocketException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
catch
(IOException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
finally
{
if
(
ftp
.isConnected()) {
try
{
ftp
.disconnect();
}
catch
(IOException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
}
}
return
success
;
}
}
前台访问配置的servlet路径即可在网页上实现下载功能
这篇博客主要介绍了如何使用Java从FTP服务器下载图片,并将其保存到客户端本地的详细步骤,结合Servlet实现文件的传输。
831

被折叠的 条评论
为什么被折叠?



