简体   繁体   中英

Issue Serializing Image Data with Angular

I have an application where allow a user to select an image, then I use ng-img-crop to allow them to crop the image. From that I have the data for the image represented as something like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAgA...

This is set to an image using the ng-src directive, like this:

<img ng-src="{{product.Image}}" />

From there I am sending the data back to my ASP.NET Web API controller to save the information in the database. My model for the product has a byte[] for the image, which is represented in the database as varbinary. Here is my model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string SerialNumber { get; set; }
    public string Notes { get; set; }
    public byte[] Image { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
    public ApplicationUser User { get; set; }
}

So, when I send the information back to my controller, here is the request information:

PUT http://localhost:20697/api/products/2 HTTP/1.1
Host: localhost:20697
Connection: keep-alive
Content-Length: 37272
Accept: application/json, text/plain, */*
Origin: http://localhost:20697
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:20697/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie:  (truncated for size)

{"Category":{"Id":5,"Name":"Graphics/Media","User":null},"Id":2,"Name":"Windows 8 x64 Professional","SerialNumber":"MN8M6","Notes":null,"Image":"data:image/png;base64,iVBORw0KGgo...(truncated for size)","CategoryId":4,"User":null}

The problem, is that if I send real data from the image as shown above, the product is always null when it gets to the controller. If I change the data send for the image to a simple string like abcd, then it goes through just fine. So I am guessing there is a serialization issue. Can someone point me to where I am going wrong here?

Thanks!

The image data is a string. You must receive it as a string and convert it back into bytes with Convert.FromBase64String()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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