Answered CloudBlob ContentType Setting..

  • lunes, 13 de febrero de 2012 9:14
     
     

    while i was used CloudBlob Object that have find error by file type.

    if it type of png is not found error, but type of jpg is found error.

    error message is "Specified value has invalid Control characters."

    [ During debugging ]

    png type file's contenttype is "image/x-png" 
    jpg type file's contenttype is "image/pjpeg" 

    why this code is raise up error ?

    ----------------------
    [ Source ]

                var blob = this.GetContainer().GetBlobReference(name);

                blob.Properties.ContentType = contentType;
               
                // create some metadata for this image
                var metadata = new NameValueCollection();
                metadata["id"] = id;
                metadata["Filename"] = fileName;
                metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

                // add and commit metadata to blob
                blob.Metadata.Add(metadata);
                blob.UploadByteArray(data);   <-- raise up here...

     

Todas las respuestas

  • lunes, 13 de febrero de 2012 10:43
     
     Respuesta propuesta

    Are you sure this is caused by the ContentType? Because image/pjpeg should be a valid content type.

    Maybe one of the other properties you're setting in the metadata holds a Control character.
    Try to clean your values first before assigning them to the metadata.

    An example of such a function can be found here: http://stackoverflow.com/questions/6799631/removing-control-characters-from-a-utf-8-string

  • martes, 14 de febrero de 2012 0:59
     
     

    well... i was try attach image file type of png and jpg.
    png type is not found error. but jpg type found error.
    so i was think that problem is raise up error from set content type context.

    [ call method ]

    protected void upload_Click(object sender, EventArgs e)
    {
     if (imageFile.HasFile)
     {
      status.Text = "Inserted [" + imageFile.FileName + "] - Content Type [" + imageFile.PostedFile.ContentType + "] - Length [" + imageFile.PostedFile.ContentLength + "]";

      // it just give content type to method from PostedFile.
      this.SaveImage(
        Guid.NewGuid().ToString(),
        imageName.Text,
        imageDescription.Text,
        imageTags.Text,
        imageFile.FileName,
        imageFile.PostedFile.ContentType,
        imageFile.FileBytes
      );

      RefreshGallery();
     }
     else
      status.Text = "No image file";
    }

    [ called method ]

    private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
    {
     // create a blob in container and upload image bytes to it
     var blob = this.GetContainer().GetBlobReference(name);

     // Content Type Set.
     blob.Properties.ContentType = contentType;
     
     // create some metadata for this image
     var metadata = new NameValueCollection();
     metadata["id"] = id;
     metadata["Filename"] = fileName;
     metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
     metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
     metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

     // add and commit metadata to blob
     blob.Metadata.Add(metadata);
     blob.UploadByteArray(data);   <-- Raise Up Error
    }

     

  • martes, 14 de febrero de 2012 6:49
    Moderador
     
      Tiene código

    Hi,

    I have test your code with a test jpg file and test parameters, and i can not reproduce your problem, it seems that your code is good (I do not know "RefreshGallery" from your code, if you think this method is important, please inform me.), so could you please provide more details about your parameters, i guess your parameters cause this problem, such as your blob container name, metadata variables, etc.

    My test code (You can test it if convenient):

      if (imageFile.HasFile)
                {
                    lbContent.Text = "Inserted [" + imageFile.FileName + "] - Content Type [" + imageFile.PostedFile.ContentType + "] - Length [" + imageFile.PostedFile.ContentLength + "]";
    
                    // it just give content type to method from PostedFile.
                    this.SaveImage(
                      Guid.NewGuid().ToString(),
                      "Name",
                      "Description",
                      "Tags",
                      imageFile.FileName,
                      imageFile.PostedFile.ContentType,
                      imageFile.FileBytes
                    );
    
                    //RefreshGallery();
                }
                else
                    lbContent.Text = "No image file";
     

            private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
            {
                client = account.CreateCloudBlobClient();
                container = client.GetContainerReference("container");
                container.CreateIfNotExist();
                var permission = container.GetPermissions();
                permission.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permission);
    
                // create a blob in container and upload image bytes to it
                var blob =container.GetBlobReference(name);
    
                // Content Type Set.
                blob.Properties.ContentType = contentType;
    
                // create some metadata for this image
                var metadata = new NameValueCollection();
                metadata["id"] = id;
                metadata["Filename"] = fileName;
                metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;
    
                // add and commit metadata to blob
                blob.Metadata.Add(metadata);
                blob.UploadByteArray(data);
            }
    

    Hope it can help you.

    Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework

  • martes, 14 de febrero de 2012 7:31
     
     

    Thanks...

    this code from microsoft's lab project...

    behind full source is here...

    if i change content type from each image files, i think this problem will be clear.

    [ Default.aspx.cs ]

    // ----------------------------------------------------------------------------------
    // Microsoft Developer & Platform Evangelism
    //
    // Copyright (c) Microsoft Corporation. All rights reserved.
    //
    // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
    // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
    // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
    // ----------------------------------------------------------------------------------
    // The example companies, organizations, products, domain names,
    // e-mail addresses, logos, people, places, and events depicted
    // herein are fictitious.  No association with any real company,
    // organization, product, domain name, email address, logo, person,
    // places, or events is intended or should be inferred.
    // ----------------------------------------------------------------------------------

    namespace RDImageGalleryWebRole
    {
        using System;
        using System.Collections.Specialized;
        using System.Configuration;
        using System.Linq;
        using System.Web.UI.WebControls;
        using Microsoft.WindowsAzure;
        using Microsoft.WindowsAzure.ServiceRuntime;
        using Microsoft.WindowsAzure.StorageClient;
        using Microsoft.WindowsAzure.StorageClient.Protocol;

        public partial class _Default : System.Web.UI.Page
        {
            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    if (!IsPostBack)
                    {
                        this.EnsureContainerExists();
                    }
                    this.RefreshGallery();
                }
                catch (System.Net.WebException we)
                {
                    status.Text = "Network error: " + we.Message;
                    if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
                    {
                        status.Text += "<br />Please check if the blob service is running at " +
                        ConfigurationManager.AppSettings["storageEndpoint"];
                    }
                }
                catch (StorageException se)
                {
                    Console.WriteLine("Storage service error: " + se.Message);
                }
            }

            protected void upload_Click(object sender, EventArgs e)
            {
                if (imageFile.HasFile)
                {
                    status.Text = "Inserted [" + imageFile.FileName + "] - Content Type [" + imageFile.PostedFile.ContentType + "] - Length [" + imageFile.PostedFile.ContentLength + "]";

                    String sContentType = String.Empty;
                   
                    this.SaveImage(
                      Guid.NewGuid().ToString(),
                      imageName.Text,
                      imageDescription.Text,
                      imageTags.Text,
                      imageFile.FileName,
                      imageFile.PostedFile.ContentType,
                      imageFile.FileBytes
                    );

                    RefreshGallery();
                }
                else
                    status.Text = "No image file";
            }

            /// <summary>
            /// Cast out blob instance and bind it's metadata to metadata repeater
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnBlobDataBound(object sender, ListViewItemEventArgs e)
            {
            }

            /// <summary>
            /// Delete an image blob by Uri
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnDeleteImage(object sender, CommandEventArgs e)
            {
            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnCopyImage(object sender, CommandEventArgs e)
            {

            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnSnapshotImage(object sender, CommandEventArgs e)
            {

            }

            private void EnsureContainerExists()
            {
                var container = GetContainer();
                container.CreateIfNotExist();

                var permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
            }

            private CloudBlobContainer GetContainer()
            {
                // Get a handle on account, create a blob service client and get container proxy
                var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var client = account.CreateCloudBlobClient();
                           
                return client.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));
            }

            private void RefreshGallery()
            {
                images.DataSource =
                  this.GetContainer().ListBlobs(new BlobRequestOptions()
                  {
                      UseFlatBlobListing = true,
                      BlobListingDetails = BlobListingDetails.All
                  });
                images.DataBind();
            }

            private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
            {
                // create a blob in container and upload image bytes to it
                var blob = this.GetContainer().GetBlobReference(name);

                blob.Properties.ContentType = contentType;
               
                // create some metadata for this image
                var metadata = new NameValueCollection();
                metadata["id"] = id;
                metadata["Filename"] = fileName;
                metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

                // add and commit metadata to blob
                blob.Metadata.Add(metadata);
                blob.UploadByteArray(data);
            }
        }
    }

  • martes, 14 de febrero de 2012 8:46
    Moderador
     
     

    Hi,

    Have your try to test my code? Or can i test your image or actual parameters value?

    The code works fine at my side, the .jpg file's content-type is "image/pjpeg".

    Hope it can help you.


    Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework

  • martes, 14 de febrero de 2012 9:20
     
     

    this is sample image.

    it's 96 dpi. 

    and case of try upload more small dpi image files,

    first chance is no error found and no upload image...

    second chace is error found...

    message is : Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

    [ Modify Source from your code ]

    // ----------------------------------------------------------------------------------
    // Microsoft Developer & Platform Evangelism
    //
    // Copyright (c) Microsoft Corporation. All rights reserved.
    //
    // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
    // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
    // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
    // ----------------------------------------------------------------------------------
    // The example companies, organizations, products, domain names,
    // e-mail addresses, logos, people, places, and events depicted
    // herein are fictitious.  No association with any real company,
    // organization, product, domain name, email address, logo, person,
    // places, or events is intended or should be inferred.
    // ----------------------------------------------------------------------------------

    namespace RDImageGalleryWebRole
    {
        using System;
        using System.Collections.Specialized;
        using System.Configuration;
        using System.Linq;
        using System.Web.UI.WebControls;
        using Microsoft.WindowsAzure;
        using Microsoft.WindowsAzure.ServiceRuntime;
        using Microsoft.WindowsAzure.StorageClient;
        using Microsoft.WindowsAzure.StorageClient.Protocol;

        public partial class _Default : System.Web.UI.Page
        {
            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    if (!IsPostBack)
                    {
                        this.EnsureContainerExists();
                    }
                    this.RefreshGallery();
                }
                catch (System.Net.WebException we)
                {
                    status.Text = "Network error: " + we.Message;
                    if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
                    {
                        status.Text += "<br />Please check if the blob service is running at " +
                        ConfigurationManager.AppSettings["storageEndpoint"];
                    }
                }
                catch (StorageException se)
                {
                    Console.WriteLine("Storage service error: " + se.Message);
                }
            }

            protected void upload_Click(object sender, EventArgs e)
            {
                if (imageFile.HasFile)
                {
                    status.Text = "Inserted [" + imageFile.FileName + "] - Content Type [" + imageFile.PostedFile.ContentType + "] - Length [" + imageFile.PostedFile.ContentLength + "]";
                   
                    //this.SaveImage(
                    //  Guid.NewGuid().ToString(),
                    //  imageName.Text,
                    //  imageDescription.Text,
                    //  imageTags.Text,
                    //  imageFile.FileName,
                    //  imageFile.PostedFile.ContentType,
                    //  imageFile.FileBytes
                    //);
                    this.SaveImage(
                        Guid.NewGuid().ToString(),
                        "Name",
                        "Description",
                        "Tags",
                        imageFile.FileName,
                        imageFile.PostedFile.ContentType,
                        imageFile.FileBytes
                    );
                   
                    // RefreshGallery();
                }
                else
                    status.Text = "No image file";
            }

            /// <summary>
            /// Cast out blob instance and bind it's metadata to metadata repeater
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnBlobDataBound(object sender, ListViewItemEventArgs e)
            {
            }

            /// <summary>
            /// Delete an image blob by Uri
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnDeleteImage(object sender, CommandEventArgs e)
            {
            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnCopyImage(object sender, CommandEventArgs e)
            {

            }

            /// <summary>
            ///
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void OnSnapshotImage(object sender, CommandEventArgs e)
            {

            }

            private void EnsureContainerExists()
            {
                var container = GetContainer();
                container.CreateIfNotExist();

                var permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
            }

            private CloudBlobContainer GetContainer()
            {
                // Get a handle on account, create a blob service client and get container proxy
                var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var client = account.CreateCloudBlobClient();
                           
                return client.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));
            }

            private void RefreshGallery()
            {
                images.DataSource =
                  this.GetContainer().ListBlobs(new BlobRequestOptions()
                  {
                      UseFlatBlobListing = true,
                      BlobListingDetails = BlobListingDetails.All
                  });
                images.DataBind();
            }

            private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
            {
                //// create a blob in container and upload image bytes to it
                //var blob = this.GetContainer().GetBlobReference(name);

                //blob.Properties.ContentType = contentType;
               
                //// create some metadata for this image
                //var metadata = new NameValueCollection();
                //metadata["id"] = id;
                //metadata["Filename"] = fileName;
                //metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                //metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                //metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

                //// add and commit metadata to blob
                //blob.Metadata.Add(metadata);
                //blob.UploadByteArray(data);

                var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var client = account.CreateCloudBlobClient();
                var container = client.GetContainerReference("container");
                container.CreateIfNotExist();
                var permission = container.GetPermissions();
                permission.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permission);

                // create a blob in container and upload image bytes to it
                var blob = container.GetBlobReference(name);
               
                // create some metadata for this image
                var metadata = new NameValueCollection();
                metadata["id"] = id;
                metadata["Filename"] = fileName;
                metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

                // add and commit metadata to blob
                blob.Metadata.Add(metadata);
                blob.UploadByteArray(data);

            }
        }
    }

  • martes, 14 de febrero de 2012 10:12
    Moderador
     
     Respondida Tiene código

    Hi,

    Do you use this sample to test?

    http://msdn.microsoft.com/en-us/wazplatformtrainingcourse_exploringwindowsazurestoragevs2010_topic3#_Toc310346229  

    I have download your image and use these RDImageGallaryWebRole sample for testing,
    I can upload your image success without any exception. Perhaps Your metadata message has some special words.

    I suggest your create a new Azure application and involve my code like this:
    Web Role:
    Default.aspx

        <asp:Button ID="btnUpload" runat="server" Text="Click to upload the default resources" onclick="btnUpload_Click" />
            <asp:FileUpload ID="imageFile" runat="server" />
        <br />
        <asp:Label ID="lbContent" runat="server" ForeColor="Red" ></asp:Label>

    Default.aspx.cs

            private static CloudStorageAccount account;
            public static CloudBlobClient client;
            public static CloudBlobContainer container;
            protected void Page_Load(object sender, EventArgs e)
            {
                account = new CloudStorageAccount(new StorageCredentialsAccountAndKey("[Your Account]", "[Your Key]"), false);
            }
    
            protected void btnUpload_Click(object sender, EventArgs e)
            {
               if (imageFile.HasFile)
                {
                    lbContent.Text = "Inserted [" + imageFile.FileName + "] - Content Type [" + imageFile.PostedFile.ContentType + "] - Length [" + imageFile.PostedFile.ContentLength + "]";
    
                    // it just give content type to method from PostedFile.
                    this.SaveImage(
                      Guid.NewGuid().ToString(),
                      "Name",
                      "Description",
                      "Tags",
                      imageFile.FileName,
                      "image/x-png",
                      imageFile.FileBytes
                    );
                }
                else
                    lbContent.Text = "No image file";
     
    
            }
    
            private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
            {
                client = account.CreateCloudBlobClient();
                container = client.GetContainerReference("container");
                container.CreateIfNotExist();
                var permission = container.GetPermissions();
                permission.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permission);
    
                // create a blob in container and upload image bytes to it
                var blob =container.GetBlobReference(name);
    
                // Content Type Set.
                blob.Properties.ContentType = contentType;
    
                // create some metadata for this image
                var metadata = new NameValueCollection();
                metadata["id"] = id;
                metadata["Filename"] = fileName;
                metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
                metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
                metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;
    
                // add and commit metadata to blob
                blob.Metadata.Add(metadata);
                blob.UploadByteArray(data);
            }

    Then please try to upload your image to see if works, if you do not have Azure account, try to use local azure emulator storage.

    Hope it can help you.


    Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework

  • martes, 14 de febrero de 2012 11:23
     
     Respondida

    Hi,

    Is there any chance that the values you're trying to save in metadata (ImageName, Description, FileName etc.) contain non-english characters? I got a forbidden error when I try to save a chinese word (你好) as metadata value for one of my blob.

    Hope this helps.

    Thanks

    Gaurav

  • miércoles, 15 de febrero de 2012 1:04
     
     

    Arwind - MSFT // Thanks i will test re-try.

    Gaurav Mantri // yes... file name is non-english. i will test re-try after change file name. Thanks.

  • martes, 21 de febrero de 2012 1:52
     
     

    i got it...!!

    i was change image name to english type.

    so do it...

    why can't support non english type file names... :(

    maybe other country site need it.

  • miércoles, 05 de septiembre de 2012 20:32
     
     
    Did you figure out how to store non-english characters in metadata?  I'd like to be able to do that too.

    • Editado akratzert miércoles, 05 de septiembre de 2012 20:32
    •