我想在没有页面刷新的情况下借助ajax或jQuery上传图像。 我的网页上有很多图片,当我点击其中的任何图片时,它会显示在图片框中。 请帮助我解决这个问题我为简单的上传代码提供了很多解决方案,但我需要这个。
答案 0 :(得分:1)
您无法使用AJAX上传文件,但您可以使用<iframe>
使其看起来就像您正在做的那样......
只需在其中创建一个包含简单表单的<iframe>
(不要忘记enctype="multipart/form-data"
)并使用它来显示文件输入。提交该表单后,只会重新加载iframe。
答案 1 :(得分:0)
答案 2 :(得分:0)
如果你在项目中使用jQuery,你实际上并不需要自己做<iframe>
这个东西,那里有很多插件。
Uploadify IMO似乎是最好的。
答案 3 :(得分:0)
由于安全原因,无法直接使用ajax进行此操作,但我已按照this excellent article (link)
中的说明完成了您在Asp.Net表单中所要求的内容<强> HTML 强> 制作ASP上传控件,iframe和启动事件的按钮
<asp:FileUpload ID="PhotoUpload" runat="server" CssClass="width100pc" onchange="submitUpload('UploadFrame', 'PhotoJsonInfo')" />
<iframe src='../Public/blank.htm' name='UploadFrame' style="display:none"></iframe>
<input type="text" id="PhotoJsonInfo" runat="server" style="display:none;" />
<强>的Javascript 强>
//Our function expects 2 parameters, the name of the disposable frame
//that we will use for the form post, as well as the id of the input control used to upload the file.
function submitUpload(frameName, uploadId)
{
document.forms[0].action = window.location;
//The magic line.. set the target of the form post to be our hidden IFrame
var defaultFrame = document.forms[0].target;
document.forms[0].target = frameName;
//We have to use a setTimeout here so that we can update the document in a separate thread
//otherwise the document wouldn't update until after the upload completed.
window.setTimeout(function()
{
var uploadControl = $get('<%= this.PhotoUpload.ClientID %>');
FacebookPreview.onImageUpdating(); //show animated loading gif
uploadControl.parentNode.replaceChild(uploadControl.cloneNode(true), uploadControl); // not sure this line is neccessary
}, 100);
//send request
document.forms[0].submit();
// reset postback
document.forms[0].target = defaultFrame;
}
<强>代码隐藏强>
protected override void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// This is only ever called via an IFrame
if (PhotoUpload.HasFile)
{
// do file saving logic here
string filePath = "..yourFullFilePathHere";
PhotoUpload.SaveAs(filePath);
string fileUrl = ... transform filePath to Url....
WebHelper.RegisterStartupScript(this, "FileUploaded", String.Format(@"window.parent.OnAfterUpload('{0}');", fileUrl));
}
}
}