2012-06-15 196 views
5

我有一個PHP網站上的jQuery文件上傳插件。jQuery文件上傳插件:如何上傳到子文件夾?

我想知道是否有可能將文件上傳到動態命名的子文件夾而不是全部進入相同的上傳文件夾?

原因是我需要一個單獨的文件夾來上傳由用戶在網站上創建的每個「項目」中的文件。例如。當用戶創建項目時,他們爲該項目上傳的所有內容都將轉到/ uploads/{$ project_uid}/{$ file_name}

我希望我已經正確地解釋了自己,如果有人能幫助我,在這裏。

謝謝!

+3

您使用哪個插件? Uploadify?如果您可以控制在JavaScript中設置要上傳到哪個路徑,則應該能夠根據其他變量動態更改該路徑,即項目ID /文件名。 – Benno

+3

你不能直接上傳到你喜歡的任何文件夾,我想他們都先進入一個普通的臨時文件夾,然後你使用move_upload_file。 – Anonymous

+0

該插件被稱爲jQuery文件上傳,可以在這裏找到:http://blueimp.github.com/jQuery-File-Upload/ – user1378715

回答

3

Firt,明顯的應當說明:您不能實際上設置上傳目的地使用JavaScript/jQuery的/ jWhateverPlugin(即從客戶端),一個明顯的安全原因。

但你可以傳遞信息到服務器端引擎(在你的情況下,PHP),它可能用它來管理上傳的實際存儲。

存在各種工具包可以幫助您,例如最初開始使用的blueimp的jQuery File UploadUploadifyBenno首次提升並似乎符合您的要求。

所以你要做的是定製客戶端大小和服務器端腳本來實現傳遞目錄變量並使用它們來定義存儲位置。重基礎上,Uploadify documentation

,並使用你的project_uid變量,這對子級是這樣的:

在客戶端(JavaScript + jQuery的+ Uploadify):

var project_uid; 
// populate project_uid according to your needs and implementation 
// befor using uploadify 

$('#file_upload').uploadify({ 
    'method'   : 'post', 

    // pass your variable to the server 
    'formData' : { 'project_uid' : project_uid }, 

    // optional "on success" callback 
    'onUploadSuccess' : function(file, data, response) { 
     alert('The file was saved to: ' + data); 
    } 
}); 

和服務器上 - (PHP + Uploadify):

// Set $someVar to 'someValue' 
$untrustedProjectUid = $_POST['project_uid']; 

// Remember to check heavily the untrusted received variable. 
// Let's pretend you checked it, it passe your tests, so you 
// initialized a trusted var with it 
$trustedProjectUid = ensureSecure($untrustedProjectUid); 

$targetFolder = '/uploads/' . $trustedProjectUid . '/' ; // Relative to the root 


if (!empty($_FILES)) { 
    $tempFile = $_FILES['Filedata']['tmp_name']; 
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; 
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name']; 

    // Validate the file type 
    $fileTypes = array('jpg','jpeg','gif','png'); // Put you allowed file extensions here 
    $fileParts = pathinfo($_FILES['Filedata']['name']); 

    if (in_array($fileParts['extension'],$fileTypes)) { 
     move_uploaded_file($tempFile,$targetFile); 
     echo $targetFolder . '/' . $_FILES['Filedata']['name']; 
    } else { 
     echo 'Invalid file type.'; 
    } 
}