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 sun.net.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 {

%>

}

%>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值