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

Angular 4多文件上传问题:文件无法追加及JSON格式传递需求

Fixing Angular 4 Multi-File Upload: Append Files & Send Target JSON Format

Hey Rajesh, let's get your upload functionality working right. You're hitting two snags: new files are overwriting old ones instead of appending, and you need to send that specific JSON structure instead of using FormData. Here's how to fix both:

First, Fix the File Overwrite Issue

The immediate problem here is a type mismatch in your myFiles array. You declared it as string[], but you're pushing File objects into it—this causes silent failures that make it look like files are being overwritten. Let's fix that first:

  1. Correct the array type in app.component.ts:

    // Replace string[] with File[] to properly store file objects
    myFiles: File[] = [];
    
  2. Clean up the getFileDetails method (optional but cleaner, and ensures no edge cases break the append):

    getFileDetails(e: Event) {
      const fileInput = e.target as HTMLInputElement;
      if (!fileInput.files) return;
      
      // Convert FileList to array and append each file to myFiles
      Array.from(fileInput.files).forEach(file => {
        this.myFiles.push(file);
      });
    }
    

    Now every time you select new files, they'll add to the existing list instead of replacing it. If you still see overwrites later, check if you're resetting myFiles somewhere else (like after upload—wait until upload succeeds to clear it!).

Next, Send the Exact JSON Structure You Need

Right now you're using FormData, but your backend expects a JSON array with attachmentName and attachedFile (which I assume is a base64 string of the file content). We need to convert each file to that format first:

Step 1: Add a helper to convert files to your target object

Add this private method to your component—it uses FileReader to turn each file into a base64 string:

private fileToUploadObject(file: File): Promise<{attachmentName: string, attachedFile: string}> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = () => {
      resolve({
        attachmentName: file.name,
        attachedFile: reader.result as string // This is the base64 string
      });
    };
    
    reader.onerror = err => reject(err);
    reader.readAsDataURL(file); // Reads file as base64
  });
}

Step 2: Rewrite the uploadFiles method to send JSON

We'll use Promise.all to convert all files at once, then send the JSON array via POST:

async uploadFiles() {
  try {
    // Convert all files in myFiles to your target JSON structure
    const uploadPayload = await Promise.all(
      this.myFiles.map(file => this.fileToUploadObject(file))
    );
    
    // Send the JSON payload to your API
    this.httpService.post('your-api-endpoint-url', uploadPayload, {
      headers: { 'Content-Type': 'application/json' } // Tell backend we're sending JSON
    }).subscribe(
      response => {
        this.sMsg = response as string;
        console.log('Upload successful:', this.sMsg);
        // Clear the file list after successful upload
        this.myFiles = [];
      },
      (err: HttpErrorResponse) => {
        console.error('Upload failed:', err.message);
      }
    );
  } catch (conversionError) {
    console.error('Failed to convert files:', conversionError);
  }
}

Quick HTML Fix

Your original HTML had an unclosed </div> tag—let's fix that too:

<div>
  <h1>{{title}}!</h1>
  <ng-container>
    <input type="file" id="file" multiple (change)="getFileDetails($event)">
    <button (click)="uploadFiles()">Upload</button>
  </ng-container>
</div>

Key Notes

  • Why no FormData? FormData is for traditional form uploads, but your backend expects a JSON array—they're incompatible formats, so we need to send raw JSON instead.
  • Base64 considerations: Base64 adds ~30% to file size, so this works best for small-to-medium files. If you're uploading large files, you might want to ask your backend to support chunked uploads instead.
  • Type safety matters: Always use proper types in Angular—using string[] for File objects was the root cause of your overwrite issue!

内容的提问来源于stack exchange,提问作者Rajesh Valluru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:41:27