繁体   English   中英

Umbraco v4对比Cute AJAX Uploader控件

[英]Umbraco v4 vs Cute AJAX Uploader Control

我有一个自定义用户控件,我在Umbraco CMS的页面中使用了该控件...自升级到版本4以来,似乎此用户控件不再起作用。

用户控件包含ajax上传程序控件(支持请求发布在这里: http : //cutesoft.net/forums/53732/ShowThread.aspx#53732 ),该控件允许用户上传图像,然后将上传的图像显示给用户。 控件和图像显示包含在UpdatePanel中,这是此问题所在的位置-似乎发送回updatePanel的数据无效,因此客户端吐出虚拟对象并引发此错误:

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

Details: Error parsing near '

<!DOCTYPE html PUBL'.

我认为这与导致Umbraco v4的母版页实现方式有关。 关于为什么会发生这种情况的任何想法,以及我可以尝试解决的想法?

仅供参考,这是一篇描述该错误及其可能原因的博客文章: http : //weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how -to-避免-it.aspx

我在updatePanel中执行任何Response.write或Response.Redirect我未使用任何响应筛选器我已禁用服务器跟踪我未使用response.transfer

但是,不管以上哪种情况,在Umbraco v3网站上使用相同的用户控件都可以正常工作,这使我相信它与v4有关。

任何建议,不胜感激

我知道整个答案并不能直接解决您的问题,而更像是一种解决方法。 这是因为我不熟悉您使用的自定义控件。 但是,今晚我将看一下您的问题,看看是否可以找到您当前使用的代码和插件的解决方案。

同时,我可能会给你一些我正在使用自己的Ajax上传的想法。 我知道这是一大堆代码,但是如果您有兴趣,可以尝试一下:)


my example case

I have an upload control in my own website and it works perfectly with umbraco. the form and upload are powered with jQuery (upload is handled by jQuery.AjaxUpload plugin)

and i created a generic handler inside my umbraco folder which handles the file on the server. creating a media item in the media library for it (and in my case beeing an avatar uploader on your profile page, it also adds the newly created mediaitem to the member's avatar property)

jQuery code: (stored in script block in the head of your page, or in a separate script)

initializeChangeAvatarForm = function() {
    var button = $('#submitChangeAvatar'), interval;
    new AjaxUpload(button,{
        action: '/umbraco/AjaxFileUpload.ashx',
        name: 'myfile',
        onSubmit : function(file, ext){
            // change button text to uploading + add class (with animating background loading image)
            button.text('Uploading').addClass('loading');
            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();
        },
        onComplete: function(file, response){
            button.text('Upload nieuw').removeClass('loading');
            // Although plugins emulates hover effect automatically,
            // it doens't work when button is disabled
            button.removeClass('hover');
            window.clearInterval(interval);
            // enable upload button
            this.enable();
        }
    });
};

$(document).ready(function(){
    initializeChangeMailForm();
});

html code in your body:

<div id="container"><h2>Upload Avatar</h2><button class="button" id="submitChangeAvatar" type="button">Upload new</button></div>

jQuery ajaxupload plugin: (/scripts/jQuery.ajaxupload.js) 'since this code is too long i added a link directly to the .js file i use 'and another link to the page where i got the plugin

handler .ashx: (stored inside /umbraco/AjaxFileUpload.ashx)

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.member;

namespace SH.umbServices
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AjaxFileUpload : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context) 
        {
            string strResponse = "error";
            try 
            {
                //string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
                //string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
                //string strSaveLocation = context.Server.MapPath("../images/temp") + "\\" + strFileName;
                //context.Request.Files[0].SaveAs(strSaveLocation);
                UmbracoSave(context);
                strResponse = "success";
            }
            catch
            { 
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(strResponse);
        }

        public bool IsReusable 
        {
            get 
            {
                return false;
            }
        }

        #region "umbMediaItem"
        protected string UmbracoSave(HttpContext context)
        {
            string mediaPath = "";

            if (context.Request.Files[0] != null)
            {
                if (context.Request.Files[0].FileName != "")
                {
                    // Find filename
                    string _text = context.Request.Files[0].FileName;
                    string _ext = Path.GetExtension(context.Request.Files[0].FileName);
                    string filename;
                    string _fullFilePath;

                    //filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
                    filename = Path.GetFileName(_text);
                    string _filenameWithoutExtention = filename.Replace(_ext, "");
                    int _p = 1212; // parent node.. -1 for media root)

                    // create the Media Node
                    umbraco.cms.businesslogic.media.Media m = umbraco.cms.businesslogic.media.Media.MakeNew(
                        _filenameWithoutExtention, umbraco.cms.businesslogic.media.MediaType.GetByAlias("image"), User.GetUser(0), _p);

                    // Create a new folder in the /media folder with the name /media/propertyid
                    System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString()));
                    _fullFilePath = System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
                    context.Request.Files[0].SaveAs(_fullFilePath);

                    // Save extension
                    //string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
                    string orgExt = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
                    orgExt = orgExt.Trim(char.Parse("."));
                    try
                    {
                        m.getProperty("umbracoExtension").Value = orgExt;
                    }
                    catch { }

                    // Save file size
                    try
                    {
                        System.IO.FileInfo fi = new FileInfo(_fullFilePath);
                        m.getProperty("umbracoBytes").Value = fi.Length.ToString();
                    }
                    catch { }

                    // Check if image and then get sizes, make thumb and update database
                    if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt + ",") > 0)
                    {
                        int fileWidth;
                        int fileHeight;

                        FileStream fs = new FileStream(_fullFilePath,
                            FileMode.Open, FileAccess.Read, FileShare.Read);

                        System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
                        fileWidth = image.Width;
                        fileHeight = image.Height;
                        fs.Close();
                        try
                        {
                            m.getProperty("umbracoWidth").Value = fileWidth.ToString();
                            m.getProperty("umbracoHeight").Value = fileHeight.ToString();
                        }
                        catch { }

                        // Generate thumbnails
                        string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
                        generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, orgExt, fileNameThumb + ".jpg");

                        image.Dispose();
                    }
                    mediaPath = "/media/" + m.Id.ToString() + "/" + filename;

                    m.getProperty("umbracoFile").Value = mediaPath;
                    m.XmlGenerate(new XmlDocument());

                    Member mbr = Member.GetCurrentMember();
                    umbraco.cms.businesslogic.property.Property avt = mbr.getProperty("memberAvatar");
                    avt.Value = m.Id;
                    mbr.XmlGenerate(new XmlDocument());
                    mbr.Save();
                    //string commerceFileName = mediaPath;
                    //CommerceSave(commerceFileName);
                }
            }
            return mediaPath;
        }

        protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
        {
            // Generate thumbnail
            float fx = (float)fileWidth / (float)maxWidthHeight;
            float fy = (float)fileHeight / (float)maxWidthHeight;
            // must fit in thumbnail size
            float f = Math.Max(fx, fy); //if (f < 1) f = 1;
            int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);

            // fixes for empty width or height
            if (widthTh == 0)
                widthTh = 1;
            if (heightTh == 0)
                heightTh = 1;

            // Create new image with best quality settings
            Bitmap bp = new Bitmap(widthTh, heightTh);
            Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            // Copy the old image to the new and resized
            Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
            g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            // Copy metadata
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo codec = null;
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType.Equals("image/jpeg"))
                    codec = codecs[i];
            }

            // Set compresion ratio to 90%
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);

            // Save the new image
            bp.Save(thumbnailFileName, codec, ep);
            bp.Dispose();
            g.Dispose();

        }
        #endregion
    }
}

I hope this shed some light on what i use.

Pfew,..那是很多代码。

我只是对在Umbraco中保存媒体感兴趣,但也很高兴看到jQuery上传。

您使用什么上传jQuery lib? 我发现服务器。

您可以使用Path.Combine,FileInfo.Extension合并if和一些额外的变量来简化代码。 但是,嘿,我有了Resharper,让我的生活更轻松。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM