用java+ftp實現檔案上傳的問題?

jetcui發表於2005-07-02
我想用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上):
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*,com.sbwl.fileup.*" errorPage="" %>
<jsp:useBean id="fileUpload" scope="page" class="com.sbwl.test.ftpUp" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>無標題文件</title>
</head>

<body>
<%
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 {
%>
<table width="652" height="87" border="1">
<tr>
<td height="81"><form action="index.jsp?action=up" method="post" name="form1" target="_blank">
<input name="filefu" type="file" id="filefu">
<input type="submit" name="Submit" value="提交">
</form></td>
</tr>
</table>
<%
}
%>
</body>
</html>

相關文章