json 将JS函数中的附件信息发送到C#方法时出错

dbf7pr2w  于 2023-08-08  发布在  C#
关注(0)|答案(1)|浏览(92)

我在JavaScript函数中向C#方法发送附件时遇到了问题。当我想把信息发送到应该保存附件信息的方法时,我遇到了一个非法调用的问题。下面是JavaScript的代码

<div class="file-input-container">
        <label for="fileInput" class="file-label">Wybierz załącznik</label>
        <br />
        <input type="file" id="fileInput" class="file-input" name="file" />
        
    </div>

    <ul id="attachment-list"></ul>
    <hr />
    <script>
        const fileInput = document.getElementById('fileInput');
        const attachmentList = document.getElementById('attachment-list');
        let selectedAttachments = [];

        fileInput.addEventListener('change', handleFileUpload);

        function handleFileUpload(event) {
            const file = event.target.files[0];
            const fileName = file.name;
            const fileType = file.type;

            const reader = new FileReader();
            reader.onload = (e) => {
                const fileContent = new Uint8Array(e.target.result);
                const attachment = {
                    name: fileName,
                    content: fileContent,
                    type: file.type
                };
                selectedAttachments.push(attachment);
                saveAttachmentsToServer(selectedAttachments);
            };
            reader.readAsArrayBuffer(file);

            const listItem = document.createElement('li');
            listItem.classList.add('attachment-item');

            const attachmentName = document.createElement('span');
            attachmentName.classList.add('attachment-name');
            attachmentName.textContent = fileName;

            const attachmentDelete = document.createElement('span');
            attachmentDelete.classList.add('attachment-delete');
            attachmentDelete.addEventListener('click', () => {
                listItem.remove();
            });

            listItem.setAttribute('data-name', fileName);
            listItem.setAttribute('data-type', file.type);

            listItem.appendChild(attachmentName);
            listItem.appendChild(attachmentDelete);
            attachmentList.appendChild(listItem);
         

            event.target.value = '';
        }
        function saveAttachmentsToServer(attachments) {
            const formData = new FormData();
            formData.append('attachments', JSON.stringify(attachments));

            $.ajax({
                url: "?handler=SaveAttachments=" ,
                data: formData,
                success: function () {
                    console.log('Załączniki zapisane');
                },
                error: function (error) {
                    console.error('Wystąpił błąd podczas zapisu załączników', error);
                }
            });
        }
    </script>

字符串
这是C#方法

public async Task<IActionResult> OnPostSaveAttachments(List<AttachmentData> attachments)
        {
            try
            {
                foreach (var attachmentData in attachments)
                {
                    var attachmentContent = attachmentData.Content;
                    if (attachmentContent != null && attachmentContent.Length > 0)
                    {
                        string attachmentName = attachmentData.Name;
                        string attachmentType = attachmentData.Type;

                        string blobName = Guid.NewGuid().ToString();

                        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
                        BlobClient blobClient = containerClient.GetBlobClient(blobName);

                        await blobClient.UploadAsync(attachmentContent, overwrite: true);

                        // Zapisz informacje o załączniku w bazie danych lub innym miejscu, np. na podstawie identyfikatora

                        Console.WriteLine("Załącznik zapisany: " + attachmentName);
                    }
                    else
                    {
                        Console.WriteLine("Błąd: Brak zawartości załącznika.");
                    }
                }

                return Page();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Błąd: " + ex.Message);
                return BadRequest("Wystąpił błąd podczas zapisywania załączników.");
            }
        }
    }

        public class AttachmentData
    {
        public string Name { get; set; }
        public Stream Content { get; set; }
        public string Type { get; set; }
    }


即使我改进了代码,使其成功上传,但在attachmetn方法中count =0仍然是一个问题。如何解决这个问题?整个项目是在ASP.NET中创建的

pprl5pva

pprl5pva1#

我认为问题出在这一部分。因为你是从JS发送字符串,但在C#中,你期待的是一个列表。

const formData = new FormData();
            formData.append('attachments', JSON.stringify(attachments));

字符串
尝试将其更改为下面的代码。

for (let i = 0; i < attachments.length; i++) {
    const attachment = attachments[i];
    formData.append('attachments[' + i + '].Name', attachment.name);
    formData.append('attachments[' + i + '].Content', attachment.content);
    formData.append('attachments[' + i + '].Type', attachment.type);
  }

相关问题