2014-05-19 48 views
0

在我的一個頁面上,我使用多個表單,每個表單都保存着特定的數據(所以有一個表單,用戶的名字,姓氏等等,還有另一個用戶的地址等等)。每個表單都有一個「保存更改」按鈕,我使用Ajax調用將數據提交給服務器。問題是 - 在其中一種形式中,用戶可以使用Bootstrap文件上傳來上傳他的圖片(所以,首先他選擇圖片,然後單擊「保存」 - 只有文件發送到服務器),但是我不能找到任何方式來做到這一點,而無需重新加載頁面。上傳沒有頁面刷新的選定圖片

首先我嘗試使用隱藏的iframe,但似乎我無法將我的文件數據複製到Iframe,所以這是不行的。

現在我想要使用此:

GithHub File Upload

但是,一旦我有它在我的網頁,引導文件上傳停止正常工作,那就是 - 我每次自動選擇一個圖片吧開始文件上傳。奇怪的部分是 - 即使沒有用於fileuploader的init代碼,它也會發生,只是包含代碼。我想建議「修復」,那就是 - 我想重寫add方法是這樣的:

$('#file').fileupload({ 
    dataType: 'json', 
    add: function (e, data) { 
     data.context = $('<button/>').text('Upload') 
     .appendTo(document.body) 
     .click(function() { 
      data.context = $('<p/>').text('Uploading...').replaceAll($(this)); 
      data.submit(); 
     }); 
    }, 
    done: function (e, data) { 
     data.context.text('Upload finished.'); 
    } 
}); 

但「加」不擊中出於某種原因...

什麼我錯在這裏做?或者有什麼其他的方式可以實現我想要的東西?

編輯1:

這裏是我使用的圖片上傳代碼:

@using (Html.BeginForm("ProfileSavePictureData", "Animator", FormMethod.Post, new { enctype = "multipart/form-data", id = "pictureDataForm" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(null, new { id = "profilePictureDataValidationSummary" }) 

    @Html.HiddenFor(x => x.UserDataId) 
    @Html.HiddenFor(x => x.UserId) 

    <div class="form-group"> 
     <div class="fileupload fileupload-new" data-provides="fileupload"> 
      <input type="hidden" value="" name="" /> 
      <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"> 
       @if (Model == null || String.IsNullOrEmpty(Model.Picture)) 
       { 
        <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image" alt=""> 
       } 
       else 
       { 
        <img src="@Model.Picture" alt="@ViewBag.PictureNotAviableLabel" alt=""> 
        @Html.HiddenFor(x => x.Picture)<br /> 
       } 
      </div> 
      <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; 
       max-height: 150px; line-height: 2px;"> 
      </div> 
      <div> 
       <span class="btn default btn-file"><span class="fileupload-new"><i class="fa fa-paper-clip"> 
       </i> 
        @ViewBag.ChoosePicture 
       </span><span class="fileupload-exists"><i class="fa fa-undo"></i> 
        @ViewBag.ChangePicture 
       </span> 
        <input type="file" class="default" name="file" /> 
       </span><a href="#" class="btn red fileupload-exists" data-dismiss="fileupload"><i 
        class="fa fa-trash-o"></i> 
        @ViewBag.RemovePicture 
       </a> 
      </div> 
     </div> 
     <span class="label label-danger"> 
      @ViewBag.InfoLabel 
     </span><span> 
      @ViewBag.PictureMinatureWarning 
     </span> 
    </div> 
    <div class="margin-top-10"> 
     <button id="btnSaveChengesProfilePictureData" type="button" class="btn btn-default">@ViewBag.SaveChangesButtonLabel</button> 
     <input type="submit" /> 
    </div> 
} 

正如你可以看到有在底部兩個按鈕 - 既不是我想要做什麼......

+0

可以告訴你你的HTML代碼?或創建jsfiddle? –

+0

@TechnoKnol: 這將是很難Jsfiddle但請參閱我的編輯 - 我添加了負責圖片上傳的部分。希望這可以幫助。提前致謝。 – user2384366

回答

0

一個關於如何使用Bootstrap,jQuery AJAX和PHP(view live demo)創建非簡單圖片上傳表單的例子。

的JavaScript:

function noPreview() { 
    $('#image-preview-div').css("display", "none"); 
    $('#preview-img').attr('src', 'noimage'); 
    $('upload-button').attr('disabled', ''); 
} 

function selectImage(e) { 
    $('#file').css("color", "green"); 
    $('#image-preview-div').css("display", "block"); 
    $('#preview-img').attr('src', e.target.result); 
    $('#preview-img').css('max-width', '550px'); 
} 

$(document).ready(function (e) { 

    var maxsize = 500 * 1024; // 500 KB 

    $('#max-size').html((maxsize/1024).toFixed(2)); 

    $('#upload-image-form').on('submit', function(e) { 

    e.preventDefault(); 

    $('#message').empty(); 
    $('#loading').show(); 

    $.ajax({ 
     url: "upload-image.php", 
     type: "POST", 
     data: new FormData(this), 
     contentType: false, 
     cache: false, 
     processData: false, 
     success: function(data) 
     { 
     $('#loading').hide(); 
     $('#message').html(data); 
     } 
    }); 

    }); 

    $('#file').change(function() { 

    $('#message').empty(); 

    var file = this.files[0]; 
    var match = ["image/jpeg", "image/png", "image/jpg"]; 

    if (!((file.type == match[0]) || (file.type == match[1]) || (file.type == match[2]))) 
    { 
     noPreview(); 

     $('#message').html('<div class="alert alert-warning" role="alert">Unvalid image format. Allowed formats: JPG, JPEG, PNG.</div>'); 

     return false; 
    } 

    if (file.size > maxsize) 
    { 
     noPreview(); 

     $('#message').html('<div class=\"alert alert-danger\" role=\"alert\">The size of image you are attempting to upload is ' + (file.size/1024).toFixed(2) + ' KB, maximum size allowed is ' + (maxsize/1024).toFixed(2) + ' KB</div>'); 

     return false; 
    } 

    $('#upload-button').removeAttr("disabled"); 

    var reader = new FileReader(); 
    reader.onload = selectImage; 
    reader.readAsDataURL(this.files[0]); 

    }); 

}); 

PHP:

<?php 
session_start(); 
if (isset($_FILES["file"]["type"])) 
{ 
    $max_size = 500 * 1024; // 500 KB 
    $destination_directory = "upload/"; 
    $validextensions = array("jpeg", "jpg", "png"); 
    $temporary = explode(".", $_FILES["file"]["name"]); 
    $file_extension = end($temporary); 
    // We need to check for image format and size again, because client-side code can be altered 
    if ((($_FILES["file"]["type"] == "image/png") || 
     ($_FILES["file"]["type"] == "image/jpg") || 
     ($_FILES["file"]["type"] == "image/jpeg") 
     ) && in_array($file_extension, $validextensions)) 
    { 
    if ($_FILES["file"]["size"] < ($max_size)) 
    { 
     if ($_FILES["file"]["error"] > 0) 
     { 
     echo "<div class=\"alert alert-danger\" role=\"alert\">Error: <strong>" . $_FILES["file"]["error"] . "</strong></div>"; 
     } 
     else 
     { 
     if (file_exists($destination_directory . $_FILES["file"]["name"])) 
     { 
      echo "<div class=\"alert alert-danger\" role=\"alert\">Error: File <strong>" . $_FILES["file"]["name"] . "</strong> already exists.</div>"; 
     } 
     else 
     { 
      $sourcePath = $_FILES["file"]["tmp_name"]; 
      $targetPath = $destination_directory . $_FILES["file"]["name"]; 
      move_uploaded_file($sourcePath, $targetPath); 
      echo "<div class=\"alert alert-success\" role=\"alert\">"; 
      echo "<p>Image uploaded successful</p>"; 
      echo "<p>File Name: <a href=\"". $targetPath . "\"><strong>" . $targetPath . "</strong></a></p>"; 
      echo "<p>Type: <strong>" . $_FILES["file"]["type"] . "</strong></p>"; 
      echo "<p>Size: <strong>" . round($_FILES["file"]["size"]/1024, 2) . " kB</strong></p>"; 
      echo "<p>Temp file: <strong>" . $_FILES["file"]["tmp_name"] . "</strong></p>"; 
      echo "</div>"; 
     } 
     } 
    } 
    else 
    { 
     echo "<div class=\"alert alert-danger\" role=\"alert\">The size of image you are attempting to upload is " . round($_FILES["file"]["size"]/1024, 2) . " KB, maximum size allowed is " . round($max_size/1024, 2) . " KB</div>"; 
    } 
    } 
    else 
    { 
    echo "<div class=\"alert alert-danger\" role=\"alert\">Unvalid image format. Allowed formats: JPG, JPEG, PNG.</div>"; 
    } 
} 
?> 

演示和源代碼,請訪問:

https://github.com/ShinDarth/Bootstrap-image-upload-form