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

Loopback连接MongoDB时文件下载损坏问题求助

Fix Corrupted File Downloads from Loopback UI's GET /containers/{container}/download/{file}

I’ve run into this exact issue before—where Loopback’s UI reports a successful response, but the downloaded file ends up corrupted, while direct browser/Postman requests work perfectly. Let’s break down the most likely causes and straightforward fixes:

1. Missing or Incorrect Response Headers

Loopback’s UI might be treating the binary file response as plain text instead of raw binary data, which mangles the file content. The fix here is to ensure your controller explicitly sets the right headers for file downloads:

In your container controller, modify the download method to add proper response headers (adjust the Content-Type based on your file type):

async downloadFile(@param.path.string('container') container: string,
                  @param.path.string('file') file: string,
                  @inject(RestBindings.Http.RESPONSE) response: Response) {
  const fileStream = await this.containerRepository.download(container, file);
  
  // Set correct Content-Type for your file (e.g., application/pdf for PDFs)
  response.set('Content-Type', 'application/pdf');
  // Force browser to download the file with the original filename
  response.set('Content-Disposition', `attachment; filename="${file}"`);
  
  return fileStream;
}

Also, verify your OpenAPI schema for the endpoint defines the binary content type correctly:

@get('/containers/{container}/download/{file}', {
  responses: {
    '200': {
      description: 'Downloaded file content',
      content: {
        'application/octet-stream': {
          schema: {
            type: 'string',
            format: 'binary'
          }
        }
      }
    }
  }
})

2. Loopback UI Uses Wrong Response Type for Binary Data

By default, Loopback’s UI might parse all responses as JSON, which is a disaster for binary files like PDFs. To fix this, you need to ensure the request uses responseType: 'blob' when fetching the file.

If you’re using a custom frontend component with Loopback’s API, adjust your fetch code like this:

async function downloadFile(container, file) {
  const response = await fetch(`/containers/${container}/download/${file}`, {
    method: 'GET',
    credentials: 'include', // Include this if your API uses authentication
  });
  
  if (!response.ok) throw new Error('Download failed: ' + response.statusText);
  
  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  
  // Create a temporary download link to trigger the browser's download dialog
  const link = document.createElement('a');
  link.href = url;
  link.download = file;
  document.body.appendChild(link);
  link.click();
  
  // Clean up temporary resources
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
}

3. Quick Debug Check

To confirm the root cause, inspect the response in Loopback UI’s network tab:

  • If the response body shows garbled text instead of raw binary data, that confirms it’s being parsed as text
  • Verify the Content-Type header matches your file type (e.g., application/pdf for PDF files)

If the headers are correct and the response is still corrupted, the culprit is almost certainly the response type handling in the UI.


内容的提问来源于stack exchange,提问作者jheel v

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:13:25