在我的一个页面上,我使用多个表单,每个表单都包含特定数据(因此有一个表单,其中包含用户的名字,姓氏等,还有另一个表单包含用户的地址,依此类推) 。每个表单都有一个"保存更改"按钮,我使用Ajax调用将数据提交到服务器。问题是 - 在其中一个表单上,用户可以使用Bootstrap文件上传来上传他的图片(所以,首先他选择图片,然后点击"保存" - 然后才将文件发送到服务器),但是我无法在不重新加载页面的情况下找到任何方法。
首先我尝试使用隐藏的iframe
,但似乎我无法将我的文件数据复制到Iframe,所以这是不行的。
现在我试图使用它:
但是,一旦我将其包含在我的页面中,Bootstrap文件上传器就会停止正常工作,也就是说 - 每次选择图片时,它都会自动启动文件上传。奇怪的是 - 即使在任何地方都没有fileuploader的初始化代码,它也会发生,只包括代码。我尝试了#34;修正",就是 - 我尝试重写这样的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.');
}
});
但是&#34;添加&#34;因某种原因没有受到打击......
我在这里做错了什么?或者还有其他方法可以实现我想要的东西吗?
编辑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&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 :(得分:1)
我曾经做过这个小小的演示。它不是最近的,但希望能指出你正确的方向。基本上通过Ajax将文件数据发送到服务器,服务器保存文件并返回路径。这样你就可以预览图像了:
答案 1 :(得分:1)
我终于设法使用这个库做了我想做的事情:
https://cmlenz.github.io/jquery-iframe-transport/
来自上页的示例代码。此库也包含在jquery-file-upload中,但该版本已修改,不适用于上页中的示例。
答案 2 :(得分: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>";
}
}
?>
演示和源代码: