2016-04-15 47 views
0

目前,我正在爲圖像文件獲取輸入的表單上工作。瀏覽圖片後上傳,我會得到圖片的ID。這是我的POST代碼。如何使用相同的ID但不同的內容進行更新?

$("#smallpicture_id").change(function() { 
    displayAndShowImage(this,'#smallimg','#smallimg'); 
}); 

$("#largepicture_id").change(function() { 
    displayAndShowImage(this,'#largeimg','#largeimg'); 
}); 

function displayAndShowImage(input,targetHtmlElementName) { 
    if (input.files && input.files[0]) { 
     var files = input.files; 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
      $(targetHtmlElementName).attr('src', 'images/uploading.gif'); 
      var formData = new FormData(); 
      formData.append('userfile',files[0],files[0].name); 
      createImage(
       config, 
       formData, 
       { 
        onSuccess : function(data) { 
         $(targetHtmlElementName).attr('src', e.target.result); 
         $.cookie(input.id, data); 
         console.log("Image has been save - Received ID: " + data + " saved in the cookie " + input.id); 
        }, 
        onError : function(jqXHR, status) { 
         $(targetHtmlElementName).attr('src', 'images/img-error.png'); 
         console.log("ERROR " + jqXHR.responseText + "\r\nstatus = " + status); 
        } 
       } 
      ); 
     } 

     reader.readAsDataURL(files[0]); 
    } 
} 

阿賈克斯

function createImage(cfg,formData,callbacks) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', cfg.url + "/image/", true); 
    xhr.onload = function() { 
     if (xhr.status === 200) { 
      // File(s) uploaded. 
      callbacks.onSuccess(xhr.responseText.trim()); 
     } else { 
      callbacks.onError(xhr); 
     } 
    }; 

    xhr.send(formData); 
} 

我的問題是我怎麼可以更新/使用該圖像給出相同的ID刪除我的形象。我已經可以做POST和GET了,但我仍然不知道如何更新和刪除。

回答

0

您可以附加兩個String在FormData查詢標識符和ID(僅在更新&的情況下刪除),像

formData.append('queryType', 'DELETE') 
formData.append('imageID', input.id) 

在服務器端代碼(如您已添加的代碼保存新的圖像)你有像這樣添加condintion

<?php 
$identifier=$_POST['queryType']; 
if($identifier=="NEW") { 
    //save file with new ID and return ID 
} elseif ($identifier=="UPDATE") 
    //update Image Data ($_FILE) with ID appended in formdata 
} elseif ($identifier=="DELETE") 
    //Delete existing image at ID specified 
} 
?> 

希望這可能有所幫助。

+0

謝謝,我會稍後再嘗試,並通知您是否有任何問題。 –

+0

你可以真正顯示這樣做嗎? –

+0

@ M.AmirQ從其他答案看來,你似乎需要客戶端腳本來更新那裏只在瀏覽器中的圖像(你有服務器端代碼就地維護數據庫)。你能否澄清我一次 –

0

您可以爲每個上傳過程賦予您的元素特定的類名,它們具有相同的ID,然後對僅具有「update-this」類名的元素運行displayAndShowImage函數。

$("#smallpicture_id").change(function() { 

    $(this).addClass("update-this"); // add update-this class 
    $(".update-this").not($(this)).removeClass("update-this"); // remove all update-this classnames from all other ones 

    // then run your function for only element which has update-this classname 
    displayAndShowImage(this,'.update-this'); 
}); 
+0

謝謝,我會稍後再試,並告訴你我是否有任何問題。 –

+0

是否有可能我想刪除舊的圖片與他們的ID和更換新的1? –

相關問題