public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath("//admin//images") + "//" + event.getFile().getFileName());
// File result = new File("D:\\Netbeans Project\\mcGrawLibPro\\mcGrawLibPro-war\\web\\item", event.getFile().getFileName());
File bg = new File(extContext.getRealPath("//admin//images")+"//macback.png");
try {
bg.renameTo(new File(extContext.getRealPath("//admin//images")+"//bg.png"));
File f1 = new File(extContext.getRealPath("//admin//images") + "//macback.png");
result.renameTo(f1);
//System.out.println(f1);
System.out.println(result);
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg = new FacesMessage("OK",
event.getFile().getFileName() + " was upload.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("Can't upload!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
我的問題是,當我上傳的圖片類型PNG如aaa.png,它可以在服務器上載,但它不能重命名,上傳aaa.png後,我重新上傳這張照片( aaa.png)它可以更改名稱,但它有2個文件,一個是aaa.png,另一個是macback.png重命名文件
我的代碼有什麼問題?
謝謝!
所以你最終只想用'bg.png'和'macback.png'完全沒有'aaa.png',對嗎? – BeemerGuy 2010-11-10 04:58:47
你好Beemer,我想重命名文件上傳aaa.png到macback.png,下面的代碼我只是測試它可以從服務器上的圖像更改爲另一個名稱,然後更改圖像上傳到macback.png。如果我工作的很好,我會在服務器上刪除bg.png – MYE 2010-11-10 14:32:48