-->

Office365 “addFileAttachmentAsync” error when doin

2019-06-11 22:04发布

问题:

I am experiencing issue with addFileAttachmentAsync. I have 2 array : embeddedFiles(containes filenames that will be attached into body) and attachments(containes filenames that will be attachment). I have got 2 for loops running for each array and they should make GET request to Exchange Server with every single file in array and get back binary file.

          for (var i = 0; i < embeddedFiles.length; i++) {
                            var attachmentName = (new Date()).getTime() + ".png";
                            var count = 0;
                            var options = { isInline: true, ContentId: attachmentName, asyncContext: { UniqueName: attachmentName } };
                            var attachmentURL = "http://" + document.location.hostname + document.location.port + '/MailForms/api/GetAttachment?' + 'AttId=' + embeddedFiles[i] + '&' + 'MwToken=' + token + '&' + 'ReqId=' + data.ReqId + '&' + 'userSmtp=' + smtp;
                            Office.context.mailbox.item.addFileAttachmentAsync(
                                attachmentURL,
                                attachmentName,
                                options,

                                function (asyncResult) {
                                    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
                                        app.showNotification('Failed to add attachment', asyncResult.error.message);
                                    }
                                    else {

                                        var szCID = asyncResult.asyncContext.UniqueName;
                                        //var szAddBodyData = "<br><div><img height=150 width=150 src='cid:" + szCID + "'></div><br>"
                                        var bizimCigid = "cid:" + szCID;
                                        var index = "" + count;
                                        var oldsource = oBody.find('.mw-images')[index].attributes[1].value;
                                        oldsource = bizimCigid;
                                        //imagesource.replaceWith(bizimCigid);
                                        //Office.context.mailbox.item.body.setSelectedDataAsync(szAddBodyData, { coercionType: Office.CoercionType.Html });
                                        oBody.find('.mw-images')[index].attributes[1].value = oldsource;
                                        //Office.context.mailbox.item.body.setSelectedDataAsync({ coercionType: Office.CoercionType.Html });

                                        viewModel.updateComposeFormLast(subject, oBody["0"].innerHTML);
                                        count = count +  1;
                                    }


                                }


                            );

    for (var i = 0; i < attachments.length; i++) {

                            var attachmentURL = "http://" + document.location.hostname + document.location.port + '/MailForms/api/GetAttachment?' + 'AttId=' + attachments[i] + '&' + 'MwToken=' + token + '&' + 'ReqId=' + data.ReqId + '&' + 'userSmtp=' + smtp;

                            Office.context.mailbox.item.addFileAttachmentAsync(
                                attachmentURL,
                                attachments[i],
                                {
                                    'asyncContext': {}
                                },
                                viewModel.getAttachmentsContent
                                );
                        }

The code above takes query string and calls addFileAttachmentAsync method. There is nothing wrong with the URL. I tried them on browser and they do get the actual file based on custom URL. getAttachmentsContent is a method just calls console.log("blah").

It works fine when add single attachment or inline image. But I need to add multiple attachments and multiple embedded images. Here are things I tried:

  1. Just adding an single attachment - works
  2. Just adding an single inline image - works
  3. Adding an image and an attachment - works but it is slow
  4. Multiple attachments and inline images - Does not work .

The error I am getting :

    error OSF.DDA.Error code 9002 message "There was an internal format error." name : "InternalFormatError"*

To me it seems when you do multiple requests of the same format, it breaks. But I am not sure why.

Any ideas?

回答1:

@Namig Ismayilov, the addFileAttachmentAsync method is async.

So to invoke multiple async calls, here are your options:

  1. Use Promises : (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
  2. Use nested function calls by invoking the next async method inside the callback of the previous one.
  3. Use recursion, with nested calls. This is just an extension of point 2 above.

For your case for instance, here's a way to attach multiple files using recursion. The caller should just invoke the method my_add_file_attachments_recursively()

function my_add_file_attachments_recursively_helper(file_attachment_arr, index, message)
{
    if (index < file_attachment_arr.length)
    {
        var file_attachment_obj = file_attachment_arr[index];

        Office.context.mailbox.item.addFileAttachmentAsync
        (
            file_attachment_obj.url,
            file_attachment_obj.name,
            {
                "asyncContext" :
                {
                    "message" : message,
                    "index" : index
                }
            },
            function (asyncResult)
            {
                var next_message = asyncResult.asyncContext.message + "id : " + asyncResult.value + " , " + "status : " + asyncResult.status + "\n";

                // add the next attachment here, recursively
                my_add_file_attachments_recursively_helper(file_attachment_arr, asyncResult.asyncContext.index + 1, next_message);
            }
        );
    }
    else
    {
        console.log(message);
    }
}

function my_add_file_attachments_recursively()
{
    var file_attachments_arr =
    [
        {
            "name" : "gold_puppy.jpg",
            "url" : "https://foo/gold_puppy.jpg"
        },
        {
            "name" : "black_puppy.jpg",
            "url" : "https://foo/black_puppy.jpg"
        },
        {
            "name" : "white_puppy.jpg",
            "url" : "https://foo/white_puppy.jpg"
        }
    ];

    my_add_file_attachments_recursively_helper(file_attachments_arr, 0, "");
}