目前我想在不使用任何插件的情况下实现图片上传。
我的上传表单如下
<form action="/Member/UploadPicture" enctype="multipart/form-data" id="uploadform" method="post">
<span>
<div class="upload" id="imgUpl">
<h3>Upload profile picture</h3>
<div class="clear5"></div>
<input type="file" name="file" id="file" />
<button class="btn-bl" id="upComplete"><span>Upload</span></button>
</div>
</span>
</form>
我的jQuery代码是:
$('#upComplete').click(function () {
$('#up').hide();
$('#upRes').show();
var form = $("#uploadform");
$.ajax({
type: "POST",
url: "/Member/UploadPicture",
data: form.serialize(),
success: function (data) {
alert(data);
}
});
$.fancybox.close();
return false;
});
如果我打开firebug,我可以看到ajax()方法做了简单的表单post(不是多部分)而POST内容是空的
是否可以使用jQuery ajax()方法上传文件,还是应该以其他方式执行此操作?
非常感谢
答案 0 :(得分:13)
jQuery ajax不支持文件上传,手动实现这可能很麻烦。我建议你看一下jQuery form插件。
当然你可以随时查看插件的源代码,看看它是如何实现的,如果你不想包含它(它使用隐藏的iFrame,因为文件不能用AJAX上传),但为什么要这样做呢你可以直接使用它: - )
以下是您的代码的示例:
$(function() {
$('#uploadform').ajaxForm();
});
还可以将上传按钮设为提交按钮:
<button class="btn-bl" id="upComplete" type="submit">
<span>Upload</span>
</button>
答案 1 :(得分:7)
AJAX
或更合适XMLHttpRequest
尚不支持文件上传。有一些解决方法,例如通过<iframe>
上传,但它相当繁琐。您的时间将更好地用于构建应用程序,而不是重新发明这些解决方案。
但如果您对内部的工作方式感到好奇,那么请随时查看一些提供此功能的插件的源代码。可以在此链接中找到一个非常简单的解释 - http://www.openjs.com/articles/ajax/ajax_file_upload/
基本上,您将表单target
更改为在<iframe>
内提交,从而避免页面刷新,并模拟AJAX,它不是真的,但是谁在乎 - 最终用户可以'告诉你。
基于iframe的上传的最小示例可能如下所示:
$("#upComplete").click(function() {
// create a dynamic iframe, or use existing one
var iframe = $("<iframe id='f' name='f' src=''>");
// attach a load event to handle response/ know about completion
iframe.load(function() { alert('complete'); });
iframe.appendTo('body');
// change form's target to the iframe (this is what simulates ajax)
$('#uploadForm').attr('target', 'f');
$('#uploadForm').submit();
});
请注意,这不会执行任何响应处理,而只是将图片发送到服务器。要处理响应,必须为iframe的load
事件编写回调函数。
答案 2 :(得分:6)
实际上有一种方法可以使用带有Firefox&gt; 3和Chrome的ajax(xmlhttp)上传文件,也可以在不使用表单和iframe的情况下上传多个文件。实际上我正在制作一个jQuery插件来做这个,很快我就会发布它。这是一个简单的例子:
var file=$('<input type=file />').get(0).files[0];
function asyncupload(file)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304)
{
//alert(xhr.responseText);
}
}
};
xhr.upload.onload=function(e)
{
$('div#axprogress').progressbar("option", "value", 100);;
};
xhr.upload.onprogress=function(e)
{
if (e.lengthComputable)
{
var perc = Math.round((e.loaded * 100) / e.total);
$('div#axprogress').progressbar("option", "value", perc);
}
};
xhr.open("POST", "upload.php?filename="+file.name,true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
xhr.send(file);
return xhr;
}
为了获取服务器端的文件,比如php,必须为upload.php执行此操作:
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize())
{
return false;
}
$target = fopen($_GET['filename'], "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
这是一个简单的想法示例,而不是完整的工作脚本。希望这可以帮助。有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
答案 3 :(得分:3)
虽然您可以自己创建multipart/form-data
请求正文以包含文件上载字段,但它无法帮助您,因为您无法从文件上载字段中读取客户端文件。
(除了使用FileList界面,但目前只支持Firefox。)
答案 4 :(得分:0)
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
<input type="button" value=" ADD " id="btncatsave" style="width: 75px" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}