【问题标题】:Uploading selected picture without page refresh上传所选图片而不刷新页面
【发布时间】:2014-05-19 12:53:46
【问题描述】:

在我的一个页面上,我使用多个表单,每个表单都包含特定的数据(因此有一个包含用户名、姓等的表单。还有一个包含用户地址等的表单)。每个表单都有一个“保存更改”按钮,我使用 Ajax 调用将数据提交到服务器。问题是 - 在其中一个表格上,用户可以上传他的图片,使用 Bootstrap 文件上传(所以,首先他选择图片,然后点击“保存” - 只有这样文件才会发送到服务器),但我不能在不重新加载页面的情况下找到任何方法。

首先我尝试使用隐藏的iframe,但我似乎无法将我的文件数据复制到 Iframe,所以这是不行的。

现在我正在尝试使用它:

GithHub File Upload

但是,一旦我将它包含在我的页面中,Bootstrap 文件上传器就会停止正常工作,也就是说 - 每次我选择一张图片时,它都会自动开始文件上传。奇怪的部分是 - 即使任何地方都没有文件上传器的初始化代码,它也会发生,只需包含代码。我尝试了建议的“修复”,即 - 我尝试像这样覆盖 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>
}

正如你所看到的,底部有两个按钮——我想要的也不是……

【问题讨论】:

  • 你能显示你的html代码吗?还是创建 jsfiddle ?
  • @TechnoKnol:Jsfiddle 很难,但是,请查看我的编辑 - 我添加了负责图片上传的部分。希望这可以帮助。提前致谢。

标签: html asp.net-mvc-4 jquery-file-upload asyncfileupload


【解决方案1】:

我曾经做过这个小演示。这不是最近的,但希望能为您指明正确的方向。基本上通过Ajax将文件数据发送到服务器,服务器保存文件并返回路径。这样您就可以预览图像:

演示: http://silviarebelo.com/demos/file_upload_ajax/

Github 项目: https://github.com/teknotica/file-upload-preview

【讨论】:

  • 谢谢,我会查一下。
【解决方案2】:

我终于设法使用这个库做我想做的事:

https://cmlenz.github.io/jquery-iframe-transport/

上面页面的示例代码。该库也包含在 jquery-file-upload 中,但该版本已被修改,无法与上述页面中的示例一起使用。

【讨论】:

    【解决方案3】:

    一个关于如何使用 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

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 2014-12-04
      • 2019-03-07
      • 2011-08-22
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多