2013-05-16 26 views
0

好吧,我在網上找到這個文件來上傳一些文件。asp文件上傳控件,哪一個應該用?

if (FileUpload1.HasFile) 
{ 
    //create the path to save the file to 
    string fileName = Path.Combine(@"E:\Project\Folders", FileUpload1.FileName); 
    //save the file to our local path 
    FileUpload1.SaveAs(fileName); 
} 

//check to make sure a file is selected 
if (FileUpload1.HasFile) 
{ 
    //create the path to save the file to 
    string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName); 
    //save the file to our local path 
    FileUpload1.SaveAs(fileName); 
} 

什麼區別,使用哪一個?我感到困惑。順便說一下,如果我可以在數據庫中存儲文件路徑,並且下次當我想刪除或查看該文件時,如何檢索該文件?所以說,首先我添加一條記錄到數據庫並上傳一個.doc文件/ excel文件,下一次當我想要編輯該記錄時,我想要檢索上傳的文件並在UI中顯示它。謝謝。

+0

使用第二個,因爲它會將相對或虛擬路徑轉換爲真實路徑本身。 .u應該從db獲得路徑並使用它來解析路徑,就像你存儲的一樣,並對它進行操作刪除等等,以顯示url =「〜/ Files/yourfilename」 – qwr

+0

如果你已經知道你的文件夾是:E :\ ftproot \ sales那麼你不需要使用Server.MapPath,如果你只有一個像〜/ folder/folder1這樣的相對虛擬路徑,並且你想知道磁盤中的真實路徑,則需要最後一個路徑... – karthi

回答

1

使用第二個,因爲它會將相對或虛擬路徑轉換爲真實路徑本身。 .u應該從db獲取路徑並使用它來解析路徑,就像你存儲的一樣,並對其進行操作刪除等,以顯示url =「〜/ Files/yourfilename」 yourfilefromdb -u從db檢索它

string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb); 
File.Delete(filepath); 

for showing 
if it accessible directly u can just write url="~/Files/yourfilefromdb" 
+0

謝謝你的工作。 – NomNomNom

0

發佈您的兩個代碼塊的唯一區別在於指定文件路徑。

在情況1中,指定了靜態位置來保存文件。如果在生產環境中保存文件的位置不同,它可能會導致問題。這將需要重建。

而在情況2中,位置是使用相對路徑指定的。因此,它將始終將文件保存在「/ Files」位置。

+0

嗯,這意味着使用第二個更好? – NomNomNom

0
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk... 

    if (FileUpload1.HasFile) 
    { 
     string fileName = Path.Combine(@"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly 
     FileUpload1.SaveAs(fileName); 
    } 

    if (FileUpload1.HasFile) 
    { 
     string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . . 
     FileUpload1.SaveAs(fileName); 
    } 
相關問題