2011-07-20 99 views
1

我需要你的幫助。這工作到目前爲止,當我添加一個文件並向它們添加文件時,我會收到警報。但是當我想改變之前的字段時,它會顯示最後一個字段的值。我嘗試過使用不同的ID:s,但我卡住了。使用javascript顯示上傳文件名的文件名稱

另外如何僅在showSr​​c()中顯示文件名?

upload.html

<form id="uploadForm" action="{% url fileman.views.upload %}" method="post" enctype="multipart/form-data">{% csrf_token %} 
<p><input type="file" name="ufile1" id="myfile1" onChange="javascript:showSrc();" size="20"><a href="#" id="myframe1"></a></p> 
<p id="addFileFild"><a href="#" id="myframe" onclick="return addFileFild();"><img src="{{ fileman_media_url }}/plus_icon.png"WIDTH=25 HEIGHT=25></a></p> 

的script.js

function addFileFild(){ 
    ufile = ufile+1; 
    myfile = myfile+1; 
    myframe = myframe+1; 
    $("#addFileFild").before('<p><input type="file" name="ufile'+ufile+'" id="myfile' +myfile+'" onChange="javascript:showSrc();" size="20"><a href="#" id="myframe' +myframe+'"></a></p>'); 
return 0; 
} 


function showSrc() { 
    document.getElementById("myframe"+myframe).href = document.getElementById("myfile" +myfile).value; 
    var theexa=document.getElementById("myframe"+myframe).href.replace("file:///",""); 
    alert(document.getElementById("myframe"+myframe).href.replace("file:///","")); 
    } 

這是我每次都得到正確的字段值:

document.getElementById("myfile" +myfile).value; 

下面是解由Dr.Molle添加了C:/ chrome和IE8 +的去除僞造路徑。

function showSrc(obj) { 
    //obj.nextSibling.href = obj.value; 
    // this is for Chrome and IE8+ excluding C:/fakepath/... 
    var filename = obj.value.replace(/^.*\\/, '') 
    //Write filename to page. 
    obj.parentNode.replaceChild(document.createElement('span'),obj.parentNode.lastChild); 
    obj.parentNode.lastChild.appendChild(document.createTextNode(filename)); 

} 
+1

文件輸入元素受**嚴重保護,因爲它直接與用戶文件交互。我非常懷疑它允許走的路。 – TJHeuvel

+0

不,我得到目的地路徑,但文件名是足夠的。我只需要知道是否有一種方法可以檢查我目前在哪個文件區,並使用showScr()顯示。如果我手動執行,我可以做到這一點,比如說,如果我設置myfile =「myfile2」,我可以更改第二個文件字段,並且它會正確顯示更改。 – leffe

回答

2

作爲參數提供輸入到showSr​​c()

onChange="showSrc(this)" 

裏面showSr​​c訪問這樣的說法:

function showSrc(obj) { 
    obj.nextSibling.href = obj.value; 
    //output the src inside the link 
    obj.nextSibling.innerHTML = ''; 
    obj.nextSibling.appendChild(document.createTextNode(obj.value)); 
    //...... 
    } 

有關的評論編輯功能:

function showSrc(obj) { 
    obj.parentNode.replaceChild(document.createElement('span'),obj.parentNode.lastChild); 
    obj.parentNode.lastChild.appendChild(document.createTextNode(obj.value)); 
} 
+0

哇,這比我所希望的還要多!它只是立即給出文件名並對正確的更改作出反應。謝謝! – leffe

+0

您對如何將這個obj值寫入我的頁面有什麼想法嗎?例如,在上傳文件字段下。 – leffe

+0

查看我的更新回答 –