我先講一下我上傳的作法~
上傳多個商品圖片的方式是
用 onchange 綁定 input file
<input multiple type="file" id="file1" name="icons[]" class="" accept="image/jpeg, image/png, image/jpg">
然後利用 FileReader 去製造預覽圖和 base64 網址
後端用 foreach 取 $_POST['icon'] 的所有 base64 並用 file_put_contents 下載到服務器上
foreach ($_POST['icon'] as $key => $value) {
      preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result);
再利用對應的網址變成是圖片網址 https://host/images/xxxx/xxx.jpg
再把第二張以上的圖片路徑資訊丟到 icon 數據表中
欄位是 product_id 和 icon
現在的問題是:
假設是要修改圖片呢?
第一個是顯示的問題,進入該圖片顯示他目前有幾個圖片
第二個問題是怎麼提出修改?
第三個是沒有修改的圖片如何略過?因為 input file 沒辦法附帶 value 值(安全問題),那我後端怎麼知道哪些有動哪些沒動?
js
$('body').on('change', '.add-btn',function(e){
    e.preventDefault();
    var id = $('.admin-upload-inline').length + 1;
    var removeBtn = $('<i class="admin-upload-remove material-icons">highlight_off</i>');
    var iconLayout = $('<div class="admin-upload-inline add-btn pointer" id="icon-layout-'+id+'">');
    var fileInput = $(
      '<input type="hidden" id="file'+id+'" name="icon[]" class="admin-upload" value="">'
    + '<img src="../images/30.png" id="pre'+id+'" class="admin-upload-review">');
    removeBtn.click(function() {
			$(this).fadeOut().parent().remove();
			var wrappers = $(".admin-upload-inline");
      var uploadInput = $('.admin-upload');
      var imgSrc = $('.admin-upload-review');
  		if (wrappers.length > 1) {
  			var newId = 1;
  			wrappers.each(function(){
  				renewId = "icon-layout-" + newId;
  				$(this).attr("id", renewId);
  				newId++;
  			});
  		}
      if (imgSrc.length > 1) {
  			var newId = 1;
  			imgSrc.each(function(){
  				renewId = "pre" + newId;
  				$(this).attr("id", renewId);
  				newId++;
  			});
  		}
      if (uploadInput.length > 1) {
  			var newId = 1;
  			uploadInput.each(function(){
  				renewId = "file" + newId;
  				$(this).attr("id", renewId);
  				newId++;
  			});
  		}
		});
    if(id < 8){
      iconLayout.append(fileInput);
  		iconLayout.append(removeBtn);
  		$(".addend-display").append(iconLayout);
    }
       var reader = new FileReader();
       reader.onload = function(e) {
         $('#pre' + id).attr('src', e.target.result);
         $('#file' + id).attr('value', e.target.result);
       }
     reader.readAsDataURL(this.files[0]);
  });
第一個是顯示的問題,進入該圖片顯示他目前有幾個圖片
Ans: 把圖片都撈出來顯示
第二個問題是怎麼提出修改?
第三個是沒有修改的圖片如何略過?因為 input file 沒辦法附帶 value 值(安全問題),那我後端怎麼知道哪些有動哪些沒動?
Ans: 2,3問題應該是一樣的,既然用了FileReader,那就是ajax的操作,data可以額外附值,把有修改圖片的product_id傳過去,不用考慮input file的value
var file = document.getElementById('_testFile').files[0];
$.ajax({
    url: "/attachmentURL",
    type: "POST",
    data: {'file' : file, 'product': [product_id1, product_id2, product_id3]},
    processData: false
});
咦?這樣要怎麼知道哪個圖片被修改了?以及我在前端要怎麼顯示?每一個照片一樣配一個 input嗎
如何圖片被修改了?user頁面操作一定會知道丫,就看你怎麼記錄而已,作法很多吧,可以參考一下現有的套件是怎麼處理的,例如:
https://blueimp.github.io/jQuery-File-Upload/