将PDF从Cloudinary转换为邮件附件将MemoryStream转换为Stream

时间:2017-07-11 12:47:08

标签: asp.net cloudinary

我正在尝试将存储在Cloudinary上的PDF转换为System.Net.Mail Attachment

 private static Attachment CreateAttachementFromMessage(Stream stream)
        {
            var memoryStream = new MemoryStream();
            stream.CopyTo(memoryStream);

            return new Attachment(
                memoryStream,
                "Anhang zur Bestellung",
                "application/pdf"
                );
        }

流:

var stream = getFileStream(resourceId);
private getFileStream(resourceId){

                var imageData=_cloudinary.GetResource(resourceId);

                if (imageData.StatusCode != HttpStatusCode.OK)
                {
                    return null;
                }

                var downloadUrl = _cloudinary.Api.UrlImgUp.Secure().BuildUrl(resourceId);

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    return null;
                }

                return DownloadStream(new Uri(downloadUrl));}


}

流不是null,但邮件内容本身似乎无效。 文件大小要小得多(因子4),无法打开。

有什么想法吗?创建流,转换流或创建附件是否有问题?

编辑: 将流复制到内存流:

https://i.stack.imgur.com/IveNn.png

编辑2:实际附件内容:

https://i.stack.imgur.com/x85AO.png

1 个答案:

答案 0 :(得分:0)

如果有人关心:

通过base64转换它可以正常工作:

using (BinaryReader b = new BinaryReader(stream))
                    {
                        byte[] binData = b.ReadBytes((int) stream.Length);
                        String result = Convert.ToBase64String(binData);

                        var decodedFile = Convert.FromBase64String(result);

                        var mediaType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg).MediaType;

                        return new Attachment(
                            new MemoryStream(decodedFile),
                            $"Anhang zur Bestellung.{mediaType}",
                            mediaType
                        );

似乎有点不必要,但方法stream.CopyTo()对我不起作用