You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSOM/JavaScript实现SharePoint列表多文件输入框上传

Solution for Uploading Files from Multiple Inputs to SharePoint List Attachments (CSOM/JavaScript)

Got it, let's figure out how to get those 6 file inputs uploading attachments to the same SharePoint list item. The key here is to first collect all the selected files from your inputs, create the list item first (since attachments need a parent item), then upload each file as an attachment to that newly created item.

Step 1: Collect All Selected Files

First, we'll grab all the file input elements and gather their selected files into a single array. We'll skip any inputs where no file was selected to avoid errors.

Step 2: Create the SharePoint List Item

Before uploading attachments, we need a list item to attach them to. We'll use CSOM to create a basic list item (you can add your own fields here as needed).

Step 3: Upload Each File as an Attachment

Once we have the list item ID, we'll loop through our collected files and use AttachmentCreationInformation to upload each one as an attachment to the new item.


Full Working Code Example

HTML (Your 6 File Inputs)

<input type="file" class="attachment-input" />
<input type="file" class="attachment-input" />
<input type="file" class="attachment-input" />
<input type="file" class="attachment-input" />
<input type="file" class="attachment-input" />
<input type="file" class="attachment-input" />
<button onclick="uploadAllFilesToSharePoint()">Upload All Attachments</button>

JavaScript (CSOM Implementation)

function uploadAllFilesToSharePoint() {
    // Step 1: Collect all selected files from inputs
    const fileInputs = document.querySelectorAll('.attachment-input');
    const filesToUpload = [];
    
    fileInputs.forEach(input => {
        if (input.files.length > 0) {
            filesToUpload.push(input.files[0]); // Grab the first file from each input (adjust if allowing multiple per input)
        }
    });

    if (filesToUpload.length === 0) {
        alert('No files selected to upload!');
        return;
    }

    // Step 2: Initialize CSOM context and get the target list
    const context = SP.ClientContext.get_current();
    const list = context.get_web().get_lists().getByTitle('Your List Name'); // Replace with your list title

    // Create a new list item (add your own field values here)
    const listItemCreateInfo = new SP.ListItemCreationInformation();
    const newItem = list.addItem(listItemCreateInfo);
    
    // Set any required fields for your list (example: Title field)
    newItem.set_item('Title', 'New Item with Multiple Attachments');
    newItem.update();

    context.load(newItem);

    // Execute the list item creation, then upload attachments
    context.executeQueryAsync(
        function() {
            const itemId = newItem.get_id();
            console.log(`List item created with ID: ${itemId}`);
            
            // Step 3: Upload each file as an attachment
            uploadAttachments(context, list, itemId, filesToUpload, 0);
        },
        function(sender, args) {
            console.error('Error creating list item:', args.get_message());
        }
    );
}

// Recursive function to upload attachments one by one (CSOM is async, so we chain them)
function uploadAttachments(context, list, itemId, files, index) {
    if (index >= files.length) {
        alert('All attachments uploaded successfully!');
        return;
    }

    const file = files[index];
    const attachmentInfo = new SP.AttachmentCreationInformation();
    
    attachmentInfo.set_fileName(file.name);
    attachmentInfo.set_contentStream(file);

    const attachments = list.getItemById(itemId).get_attachmentFiles();
    const newAttachment = attachments.add(attachmentInfo);

    context.load(newAttachment);

    context.executeQueryAsync(
        function() {
            console.log(`Uploaded file: ${file.name}`);
            // Move to next file
            uploadAttachments(context, list, itemId, files, index + 1);
        },
        function(sender, args) {
            console.error(`Error uploading ${file.name}:`, args.get_message());
            // Even if one fails, you can choose to continue with others
            uploadAttachments(context, list, itemId, files, index + 1);
        }
    );
}

Key Notes for Your Use Case

  • Replace 'Your List Name' with the actual title of your SharePoint list.
  • If your list requires other mandatory fields, add them to the newItem.set_item() section (e.g., newItem.set_item('Description', 'Sample description');).
  • The code uses a recursive approach to handle async CSOM calls, ensuring files upload one after another. If you prefer using Promises/async-await, you can wrap the CSOM calls in promises for cleaner code.
  • We use a class selector .attachment-input to target all 6 file inputs—this is cleaner than targeting individual IDs, but you can adjust to use IDs if needed (e.g., document.querySelectorAll('#file1, #file2, ...')).

This approach should solve your issue of collecting files from multiple inputs and attaching them to the same SharePoint list item. Let me know if you run into any specific errors with your setup!

内容的提问来源于stack exchange,提问作者saumya bhargava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:57:21