RGdent RGdent - 5 months ago 42
AngularJS Question

Attach Image to email from byte

I am busy trying to understand how to work with images from a

website -> service -> email
.

What I have done so far is converting the image to
base64
then uploading it to my service. Next I convert it to a byte array and then store it into my database.

At the same time when inserting the byte into my database I want to send the image by attaching it to an email.

At this time the attachment is only a file that I cannot open, so I guess it is just a byte array and not an Image.

C#

public string SendEmail(string send)
{
try
{
TestDb db = new TestDb();

TestImage result = new TestImage();
string[] arData = send.Split('|');

byte[] bytes = new byte[arData[0].Length * sizeof(char)];
System.Buffer.BlockCopy(arData[0].ToCharArray(), 0, bytes, 0, bytes.Length);

result.TestImg = bytes;
result.TestId = int.Parse(arData[1].ToString());

db.TestImage.Attach(result);
db.TestImage.Add(result);
db.SaveChanges();

string foto = "name";

Attachment att = new Attachment(new MemoryStream(bytes), foto);

MailMessage mail = new MailMessage();
NetworkCredential cred = new NetworkCredential("Test@gmail.com", "Test123");

mail.To.Add("Test@gmail.com");
mail.Subject = "subject Test";
mail.Attachments.Add(att);
mail.From = new MailAddress("Test@gmail.com");
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Send(mail);
return result.Id.ToString();
}
catch (Exception)
{

throw;
}
}


Angularjs

$scope.link = '\img\ionic.png';
var imageData=$base64.encode($scope.link);

$scope.sendimg = function() {

console.log(imageData);
$http.post("http://localhost:53101/TruckService.svc/sendEmail/" + imageData + '|' + 1
)
.success(function(data) {
})

.error(function(data) {
console.log("failure");
})
}

Answer

I think the problem is with converting image to base64. So check whether you have correct image in imageData by convert it back to an image.

You can use online tools to converto base64 to image Link

So if it's the problem, try to convert your image as below,

function toDataUrl(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

toDataUrl('url', function(base64Img){
    // Base64DataURL
});
Comments