将图像附加到电子邮件并存储到数据库

时间:2020-01-31 03:50:17

标签: c# asp.net

我有一个表格,我想将上传的图像存储到数据库中并将这些图像发送到邮件中。

首先,我将图像存储在数据库中,然后将图像附加到正在发送的邮件中,但是我的问题是我没有在邮件中获取上载的图像。显示错误

我们不支持此文件格式

将图像转换为二进制格式的代码:

Byte[] bytImage = new byte[] { 1 };
Byte[] bytImage1 = new byte[] { 1 };
Byte[] bytImage2 = new byte[] { 1 };
Byte[] bytImage3 = new byte[] { 1 };
Byte[] bytImage4 = new byte[] { 1 };

for (var x = 0; x < Request.Files.AllKeys.Length; x++)
{
   HttpPostedFile file = Request.Files[Request.Files.AllKeys[x]];

   if (file != null && file.ContentLength > 0)
   {
       try
       {
           HttpPostedFile objHttpPostedFile = file;
           int intContentlength = objHttpPostedFile.ContentLength;

           if (x == 0)
           {
               bytImage = new Byte[intContentlength];
               objHttpPostedFile.InputStream.Read(bytImage, 0, intContentlength);
           }
           else if (x == 1)
           {
               bytImage1 = new Byte[intContentlength];
               objHttpPostedFile.InputStream.Read(bytImage1, 0, intContentlength);
           }
           else if (x == 2)
           {
               bytImage2 = new Byte[intContentlength];
               objHttpPostedFile.InputStream.Read(bytImage2, 0, intContentlength);
           }
           else if (x == 3)
           {
               bytImage3 = new Byte[intContentlength];
               objHttpPostedFile.InputStream.Read(bytImage3, 0, intContentlength);
           }
           else if (x == 4)
           {
               bytImage4 = new Byte[intContentlength];
               objHttpPostedFile.InputStream.Read(bytImage4, 0, intContentlength);
           }
       }
       catch (Exception ex)
       {
           throw ex;
       }
   }
}

将图像发送到邮件的代码:

message.IsBodyHtml = true;

for (int x = 0; x < Request.Files.Count; x++)
{
    HttpPostedFile PostedFile = Request.Files[x];

    if (PostedFile != null && PostedFile.ContentLength > 0)
    {
        try
        {          
            message.Attachments.Add(new 
            Attachment(PostedFile.InputStream,PostedFile.FileName));
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

0 个答案:

没有答案