Image uploader in ajax or Jquery
I want to upload image with the help of ajax or jQuery without page refreshing. I have lot of images in my web page and when i will click any of them then it will show in image box. Please help me for this problem 开发者_开发问答i get lot of solution for simple uploading code but i need this.
You can't upload files with AJAX, but you can use an <iframe>
to make it look as though that's what you're doing...
Just create an <iframe>
with a simple form inside it (don't forget the enctype="multipart/form-data"
) and use that to display the file input. When that form is submitted, only the iframe will reload.
AJAX Upload jQuery plugin
Multiple File Upload Plugin
If you use jQuery in your project you don't actually need to do <iframe>
thing on your own, there are plenty of plugins for it.
Uploadify IMO seems to be the best one.
This can't be done directly with ajax due to secutiry reasons, but I have done what you're asking for in an Asp.Net form by following the directions in this excellent article (link)
HTML Make an ASP upload conrol, an iframe and a button to kick off the event
<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;
}
CodeBehind
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));
}
}
}
精彩评论