2014-10-07 47 views
1

使用的Servlet使用的代碼如下,我上傳文件重命名文件::的Java文件上傳上載

FileItem fi = (FileItem) i.next(); 
String fileName = fi.getName(); 
out.print("FileName: " + fileName); 
String contentType = fi.getContentType(); 
boolean isInMemory = fi.isInMemory(); 
long sizeInBytes = fi.getSize(); 

if (fileName == null || fileName == "") { 
    resumefilepath = ""; 
} else { 

    resumeflag = 1; 

    if (fileName.lastIndexOf("\\") >= 0) { 

     file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\"))); 

    } else { 

     file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); 

    } 

    fi.write(file); 

我所得到的是我的文件得到正確上傳。我需要以不同的名稱上傳我的文件,但請確保不應更改文件內容。假設我有一個圖像'A.png',那麼它應該保存爲'B.png'。請幫助傢伙?我曾嘗試這樣的:

File f1 = new File("B.png"); 
// Rename file (or directory) 
file.renameTo(f1); 

fi.write(file); 

但不工作

+0

使用['文件#renameTo()'](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo%28java.io.File%29)重命名文件。 – Braj 2014-10-07 11:11:12

+0

@Braj你可以編輯我的代碼並粘貼爲答案? – androidGenX 2014-10-07 11:11:51

+0

@Braj在其他例子中,他們正在創建新文件,然後保存,在這種情況下,它會丟失我的文件的內容,我需要保持我的頁面內容在那裏!內容不得更改只有名稱應該更改 – androidGenX 2014-10-07 11:16:43

回答

1

假設你指的是Apache的百科全書,你只是在你傳遞給FileItem.write什麼File例如控制FileItem。此時,File對象只是一個抽象名稱,該文件將由該方法創建。

它是您的代碼,它從FileItem中讀取名稱並構造一個具有相同名稱的File對象。你不必這樣做。所以當你通過new File("B.png")write方法FileItem代表上傳A.png的內容將被保存在文件B.png


例如,做字面上你問什麼,你可以改變線

fi.write(file); 

if(file.getName().equals("A.png")) file=new File(file.getParentFile(), "B.png"); 
fi.write(file); 

你的代碼的簡化版本可能看起來像:

String fileName = fi.getName();// name provided by uploader 
if (fileName == null || fileName == "") { 
    resumefilepath = ""; 
} else { 
    // convert to simple name, i.e. remove any prepended path 
    fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)+1); 
    // your substitution: 
    if(fileName.equalsIgnoreCase("A.png")) fileName="B.png"; 
    // construct File object 
    file = new File(resumePath, fileName); 
    // and create/write the file 
    fi.write(file); 
} 
+0

@Hogler好友是的我正在使用pache Commons FileItem。你能告訴我怎樣才能編輯我的代碼來做同樣的事情?我不是像你這樣的專家。請幫助我的好友 – androidGenX 2014-10-07 13:34:32

+0

@androidGenX:答案已經更新。 – Holger 2014-10-07 13:42:35

+0

@Hogler兄弟同樣發行它的上傳,但名稱不變! – androidGenX 2014-10-07 14:05:28