3

I’m trying to implement custom save action for Sitecore 10 Experience forms. My form has several single line text fields and a file uploader field. I can read the single line text fields with out any issues. But when I try to read the file uploader field value and convert the InputStream (System.IO.Stream) of the file upload field into a byte array, it always gives me an empty byte array.

I tried several mechanisms of converting InputStream into a byte array but none of them gives me any results.

I get the feeling that issue is not in the mechanism I use to convert InputStream into byte array but in the FormSubmitContext data in the submit action.

Here is the code snippet of the custom save action to read the file uploader field value and convert into a byte array.

public class CustomSaveActionForFileUploads : SubmitActionBase<string>
{
    public CustomSaveActionForFileUploads(ISubmitActionData submitActionData) : base(submitActionData)
    {
    }

    protected override bool TryParse(string value, out string target)
    {
        target = string.Empty;
        return true;
    }

    protected override bool Execute(string data, FormSubmitContext formSubmitContext)
    {
        IList<IViewModel> viewModels = formSubmitContext.Fields;
        foreach (IViewModel viewModel in viewModels)
        {
            FileUploadViewModel fileUploadViewModel = viewModel as FileUploadViewModel;

            if (fileUploadViewModel != null || fileUploadViewModel.Files != null)
            {
                foreach (HttpPostedFileBase tempFile in fileUploadViewModel.Files)
                {
                    byte[] result;
                    using (var streamReader = new MemoryStream())
                    {
                        tempFile.InputStream.CopyTo(streamReader);
                        result = streamReader.ToArray();
                    }

                    //Here goes the code about using the byte array 
                }
            }                               
        }
            return true;
    }
}

Has anybody had any idea what’s going on with the Sitecore experience forms file uploader field values?

3

The Save Data submit action of the Sitecore Forms is the first submit action that reads the input stream of the uploaded files and leaves the position of the stream at its final position.

If you want to read again the input stream of the uploaded files in a custom submit action, you need to reset the input stream position to its initial value (0) before reading it again:

var tempFileInputStream = tempFile.InputStream;
tempFileInputStream.Position = 0;
tempFileInputStream.CopyTo(streamReader);
1
  • Superhappy to notice this when it was asked, saved my ass today :)
    – asontu
    Mar 16 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.