當前位置:首頁 » 文件傳輸 » 獲取ftp絕對路徑
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

獲取ftp絕對路徑

發布時間: 2023-08-01 09:16:08

A. c# 判斷 遠程ftp上的文件是否存在

比如伺服器上upfile文件夾下有個文件叫1.txt
if (File.Exists(HttpContext.Current.Server.MapPath("upfile/") + "\\" + "1.txt"))
//HttpContext.Current.Server.MapPath(相對路徑):把相對路徑轉為伺服器上的絕對路徑。File.Exists(絕對路徑):檢查是否存在絕對路徑指向的文件或目錄。

B. java ftp可以直接轉絕對路徑么 D:\\FT\GM

ftp伺服器的目錄不是你來設置的,你只相當於是一個訪問ftp的客戶端,所以你這里連接上ftp伺服器後到了ftp的根目錄,你就是要切換也只能寫/XXXX,不可以寫絕對路徑。

C. 如何獲取上傳文件的絕對路徑

<input id="myfile" type="file" />
<br />
<img src="" alt="Image to be upload." />
<div id="info"></div>
<script type="text/javascript">
var dFile = document.getElementById('myfile');
var dImg = document.getElementsByTagName('img')[0];
var dInfo = document.getElementById('info');
dFile.onchange = function(){
if(!dFile.value.match(/.jpg|.gif|.png|.bmp/i)){alert('File type must be: .jpg, .gif, .bmp or .png !');return;}
if(dFile.files){
dImg.src = dFile.files[0].getAsDataURL();
alert(dImg.src);
}else if(dFile.value.indexOf('\\') > -1 || dFile.value.indexOf('\/') > -1){
dImg.src = dFile.value;
alert(dImg.src);
}
}
</script>
輸出 完整路徑。

D. FtpClient

當時我用SUN 的FtpClient.get()方法下載文件是有問題的,我推薦你用org.apache.commons.net.ftp.FTPClient下載文件,可以解決中文文件下載問題,你可以去我博客里看看哦:http://hi..com/renliangli/blog/item/6ccb6b3a049d95c9d46225a5.html,文章摘給你吧:
現在就來看下我解決的代碼吧,希望對遇到同樣問題的人有點幫助。

1)把ftp地址中的文件保存到本地的java類源碼:

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class Ftp {

/**
* Description: 從FTP伺服器下載文件
* @param ip FTP伺服器的ip地址
* @param port FTP伺服器埠,默認為:21
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param remotePath FTP伺服器上的相對路徑
* @param fileName 要下載的文件名
* @param localPath 下載後保存到本地的路徑
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//下面三行代碼必須要,而且不能改變編碼格式,否則不能正確下載中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");

//如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}

ftp.changeWorkingDirectory(remotePath);//轉移到FTP伺服器目錄
FTPFile[] fs = ftp.listFiles();

for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){

File localFile = new File(localPath+File.separator+ff.getName());
//
OutputStream is = new FileOutputStream(localFile);

//注意此處retrieveFile的第一個參數由GBK轉為ISO-8859-1編碼。否則下載後的文件內容為空。
//原因可能是由於aix系統默認的編碼為ISO-8859-1
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
is.close();
}
}

ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Ftp.downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活碼.txt", "C:");

}

}

2)將ftp資源以文件流的方式打開,由用戶決定保存在本地何處,程序運行後可以從IE跳出框中打開或者保存的Action代碼,利用Struts1寫的:

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.mocha.test;

import java.io.IOException;

import java.io.OutputStream;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DownloadAction extends Action{

/** *//**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException{

OutputStream os=null;

try {

os = response.getOutputStream();

response.reset();

downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活碼.txt",os,response);

} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
os.close();

} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return null;

}

/**
* Description: 從FTP伺服器下載文件
* @param ip FTP伺服器ip地址
* @param port FTP伺服器埠,默認為21
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param remotePath 附件在FTP伺服器上的絕對路徑
* @param fileName 要下載的文件名
* @param outputStream 輸出流
* @param response
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath
,String fileName,OutputStream outputStream,HttpServletResponse response) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//下面三行代碼必須要,而且不能改變編碼格式
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");

//如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}

ftp.changeWorkingDirectory(remotePath);//轉移到FTP伺服器目錄
FTPFile[] fs = ftp.listFiles();

for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){

String filename = fileName;
//這個就就是彈出下載對話框的關鍵代碼
response.setHeader("Content-disposition",
"attachment;filename=" +
URLEncoder.encode(filename, "utf-8"));
//將文件保存到輸出流outputStream中
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
outputStream.flush();
outputStream.close();
}
}

ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}

差點忘了利用ftpclient要用到的jar包了,呵呵,就這兩個了:commons-net-1.4.1.jar、jakarta-oro-2.0.8.jar

對了我用的jdk是1.4的。所以commons-net-1.4.1.jar用了這個版本比較老的。

E. java獲取ftp文件路徑怎麼寫

package com.weixin.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.weixin.constant.DownloadStatus;
import com.weixin.constant.UploadStatus;

/**
* 支持斷點續傳的FTP實用類
* @version 0.1 實現基本斷點上傳下載
* @version 0.2 實現上傳下載進度匯報
* @version 0.3 實現中文目錄創建及中文文件創建,添加對於中文的支持
*/
public class ContinueFTP {
public FTPClient ftpClient = new FTPClient();

public ContinueFTP(){
//設置將過程中使用到的命令輸出到控制台
this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
}

/**
* 連接到FTP伺服器
* @param hostname 主機名
* @param port 埠
* @param username 用戶名
* @param password 密碼
* @return 是否連接成功
* @throws IOException
*/
public boolean connect(String hostname,int port,String username,String password) throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
return true;
}
}
disconnect();
return false;
}

/**
* 從FTP伺服器上下載文件,支持斷點續傳,上傳百分比匯報
* @param remote 遠程文件路徑
* @param local 本地文件路徑
* @return 上傳的狀態
* @throws IOException
*/
public DownloadStatus download(String remote,String local) throws IOException{
//設置被動模式
ftpClient.enterLocalPassiveMode();
//設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatus result;

//檢查遠程文件是否存在
FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length != 1){
System.out.println("遠程文件不存在");
return DownloadStatus.Remote_File_Noexist;
}

long lRemoteSize = files[0].getSize();
File f = new File(local);
//本地存在文件,進行斷點下載
if(f.exists()){
long localSize = f.length();
//判斷本地文件大小是否大於遠程文件大小
if(localSize >= lRemoteSize){
System.out.println("本地文件大於遠程文件,下載中止");
return DownloadStatus.Local_Bigger_Remote;
}

//進行斷點續傳,並記錄狀態
FileOutputStream out = new FileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=localSize /step;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes,0,c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println("下載進度:"+process);
//TODO 更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
boolean isDo = ftpClient.completePendingCommand();
if(isDo){
result = DownloadStatus.Download_From_Break_Success;
}else {
result = DownloadStatus.Download_From_Break_Failed;
}
}else {
OutputStream out = new FileOutputStream(f);
InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=0;
long localSize = 0L;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes, 0, c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println("下載進度:"+process);
//TODO 更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if(upNewStatus){
result = DownloadStatus.Download_New_Success;
}else {
result = DownloadStatus.Download_New_Failed;
}
}
return result;
}

/**
* 上傳文件到FTP伺服器,支持斷點續傳
* @param local 本地文件名稱,絕對路徑
* @param remote 遠程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
* @return 上傳結果
* @throws IOException
*/
public UploadStatus upload(String local,String remote) throws IOException{
//設置PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
//設置以二進制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatus result;
//對遠程目錄的處理
String remoteFileName = remote;
if(remote.contains("/")){
remoteFileName = remote.substring(remote.lastIndexOf("/")+1);
//創建伺服器遠程目錄結構,創建失敗直接返回
if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){
return UploadStatus.Create_Directory_Fail;
}
}

//檢查遠程是否存在文件
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length == 1){
long remoteSize = files[0].getSize();
File f = new File(local);
long localSize = f.length();
if(remoteSize==localSize){
return UploadStatus.File_Exits;
}else if(remoteSize > localSize){
return UploadStatus.Remote_Bigger_Local;
}

//嘗試移動文件內讀取指針,實現斷點續傳
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

//如果斷點續傳沒有成功,則刪除伺服器上文件,重新上傳
if(result == UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
return UploadStatus.Delete_Remote_Faild;
}
result = uploadFile(remoteFileName, f, ftpClient, 0);
}
}else {
result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
}
return result;
}
/**
* 斷開與遠程伺服器的連接
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}

/**
* 遞歸創建遠程伺服器目錄
* @param remote 遠程伺服器文件絕對路徑
* @param ftpClient FTPClient對象
* @return 目錄創建是否成功
* @throws IOException
*/
public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){
//如果遠程目錄不存在,則遞歸創建遠程伺服器目錄
int start=0;
int end = 0;
if(directory.startsWith("/")){
start = 1;
}else{
start = 0;
}
end = directory.indexOf("/",start);
while(true){
String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else {
System.out.println("創建目錄失敗");
return UploadStatus.Create_Directory_Fail;
}
}

start = end + 1;
end = directory.indexOf("/",start);

//檢查所有目錄是否創建完畢
if(end <= start){
break;
}
}
}
return status;
}

/**
* 上傳文件到伺服器,新上傳和斷點續傳
* @param remoteFile 遠程文件名,在上傳之前已經將伺服器工作目錄做了改變
* @param localFile 本地文件File句柄,絕對路徑
* @param processStep 需要顯示的處理進度步進值
* @param ftpClient FTPClient引用
* @return
* @throws IOException
*/
public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{
UploadStatus status;
//顯示進度的上傳
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile,"r");
OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1"));
//斷點續傳
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process = remoteSize /step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while((c = raf.read(bytes))!= -1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes / step != process){
process = localreadbytes / step;
System.out.println("上傳進度:" + process);
//TODO 匯報上傳狀態
}
}
out.flush();
raf.close();
out.close();
boolean result =ftpClient.completePendingCommand();
if(remoteSize > 0){
status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else {
status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
return status;
}

public static void main(String[] args) {
ContinueFTP myFtp = new ContinueFTP();
try {
System.err.println(myFtp.connect("10.10.6.236", 21, "5", "jieyan"));
// myFtp.ftpClient.makeDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(new String("愛你等於愛自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\\yw.flv", "/yw.flv",5));
// System.out.println(myFtp.upload("E:\\愛你等於愛自己.mp4","/愛你等於愛自己.mp4"));
//System.out.println(myFtp.download("/愛你等於愛自己.mp4", "E:\\愛你等於愛自己.mp4"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("連接FTP出錯:"+e.getMessage());
}
}
}

F. 文件上傳到ftp伺服器的路徑問題

把你要傳的東西保存到桌面,打開ftp左面是桌面,電腦圖標的是你的桌面,右面是ftp像球一樣的東西。在左側桌面找到剛才你保存桌面的東西,然後右鍵傳送。