900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java实现ftp文件上传失败_用java+ftp实现文件上传的问题?

java实现ftp文件上传失败_用java+ftp实现文件上传的问题?

时间:2020-06-15 20:06:00

相关推荐

java实现ftp文件上传失败_用java+ftp实现文件上传的问题?

我想用java实现一个文件上传的类,但现在如果客户端上传一个文件时,如果在服务器上相同的路径下如果没有该文件则上传不成功,该怎么办啊,希望大大们帮帮忙小弟感激不尽^_^。代码如下:

package com.test.fileup;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import .ftp.FtpClient;

public class ftpUp {

public ftpUp() {

}

public static FtpClient m_client;

public static void disconnect()

{

if (m_client != null)

{

try

{

m_client.closeServer();

}

catch (IOException ex)

{

}

m_client = null;

}

}

public static boolean connect(String sHost, String user,String password ,String sDir)

{

try

{

m_client = new FtpClient(sHost);

m_client.login(user, password);

m_client.cd(sDir);

m_client.binary();

}

catch (Exception ex)

{

return false;

}

return true;

}

public static boolean putFiletoServer(String m_sLocalFile,String m_sHostFile)

{

if (m_sLocalFile.length()==0)

{

return false;

}

byte[] buffer = new byte[10240];

try

{

File f = new File(m_sLocalFile);

int size = (int)f.length();

FileInputStream in = new FileInputStream(m_sLocalFile);

OutputStream out = m_client.put(m_sHostFile);

int counter = 0;

while(true)

{

int bytes = in.read(buffer);

if (bytes < 0)

break;

out.write(buffer, 0, bytes);

counter += bytes;

}

out.close();

in.close();

}

catch (Exception ex)

{

return false;

}

return true;

}

public static boolean putFile(String pathname,String ftpServer, String ftpUser,

String ftpPasswd, String ftpPath)

{

if (!connect(ftpServer,ftpUser,ftpPasswd,ftpPath))

{

return false;

}

int pos = pathname.lastIndexOf("/");

int len = pathname.length();

String filename = pathname.substring(pos+1,len);

if (!putFiletoServer(pathname,filename))

{

return false;

}

disconnect();

return true;

}

}

下面是jsp网页上传页面(ftp服务器在192.168.0.1上):

无标题文档

if (request.getParameter("action").equals("up")){

try {

if (fileUpload.connect("192.168.0.1","fileftp","123456","I:/fileup")){

out.println("connected");

}

else {

out.println("disconnected");

}

String realpath = new String(request.getParameter("filefu").getBytes("ISO-8859-1"));

if (fileUpload.putFile(""+realpath+"","192.168.0.1","fileftp","123456","I:/fileup")) {

out.println("uploaded");

}

else {

out.println("unuploaded");

}

}

catch (Exception e){

out.print(e);

}

} //action=up

else {

%>

}

%>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。