代码之家  ›  专栏  ›  技术社区  ›  Pankaj Mishra

Ajax或jQuery中的图像上载程序

  •  0
  • Pankaj Mishra  · 技术社区  · 15 年前

    我想在Ajax或jQuery的帮助下上载图像,而不刷新页面。 我的网页中有很多图片,当我单击其中任何一个图片时,它将显示在图片框中。 请帮我解决这个问题,我有很多简单的上传代码的解决方案,但我需要这个。

    4 回复  |  直到 15 年前
        2
  •  1
  •   Greg    15 年前

    不能使用Ajax上载文件,但可以使用 <iframe> 让它看起来像你正在做的…

    创建一个 <iFrAME> 里面有一个简单的形式(不要忘记 enctype="multipart/form-data" )并使用它来显示文件输入。提交该表单时,将仅重新加载iframe。

        3
  •  0
  •   Dmitry Gladkov    15 年前

    如果在项目中使用jquery,实际上不需要这样做 <iframe> 你自己做的,有很多插件。

    Uploadify 在我看来是最好的。

        4
  •  0
  •   dano    15 年前

    由于安全原因,这无法直接使用Ajax完成,但我已经按照中的说明在ASP.NET窗体中完成了您所要求的操作。 this excellent article (link)

    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));
            }
        }
    }